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

InputBox in C#

By , 21 Apr 2005
 

Sample Image - InputBox.gif

Introduction

Visual Basic 6.0 has an InputBox() function, Visual Basic .NET has one but in C# you don't. You can easily solve this by adding a reference to 'Microsoft.VisualBasic.dll' and using the static method 'Microsoft.VisualBasic.Interaction.InputBox()'.

See reference to MSDN 2001 in VB help.

InputBox Function

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a string containing the contents of the text box.

Syntax
InputBox(prompt[, title] [, default] [, xpos] [, ypos] [, helpfile, context])

The InputBox function syntax has these named arguments: see the help file MSDN\2001OCT\1033.

In the VB 6.0, there were the title, default, xpos and ypos optional values to the call of InputBox function. It is the same thing I have made.

But in this example we make ours own.

InputBox Class

The InputBox class is a public class there are not inherited from System.Windows.Forms.Form class. You use it by calling the static function name 'Show' like we also do in MessageBox. This method is returning a public InputBoxResult. This object has two public properties one called Text with a string and a ReturnCode.

There is an enum. It the same as the MessageBox returns, but the InputBox only returns these two parameters, DialogResult.OK or DialogResult.Cancel.

See the class header:

InputBox Class Image

Usage

You activate the InputBox by calling the static Show() method. It has one required and four optional arguments (using overloading).

Why there are so many new lines in the prompt argument is that, the old VB 6.0 made the InputBox form bigger after the size of the prompt argument.

private void button1_Click(object sender, System.EventArgs e)
{
    // This test that the InputBox can handle more newline than one.
    InputBoxResult test = InputBox.Show("Prompt" + "\n" + "DDDD" + 
                  "Prompt" + "\n" + "DDDD" +
                  "Prompt" + "\n" + "DDDD" + "Prompt" + "\n" + "DDDD" +
                  "Prompt" + "\n" + "DDDD" +
                  "Prompt" + "\n" + "DDDD"
                  ,"Title","Default",100,0); 

    if( test.ReturnCode == DialogResult.OK )
        MessageBox.Show(test.Text);
} 

The best of all is that the drop down list there comes from the InputBox is very small. If we have inherited from Windows.Form then it will have been bigger.

InputBox drop down list Image

This is one of the methods in the InputBox class where we assign values to all the properties in the control. It regulates the InputBox size and the prompt textbox size based on the size of the prompt input string.

static private void LoadForm()
{
    OutputResponse.ReturnCode = DialogResult.Ignore;
    OutputResponse.Text = string.Empty;

    txtInput.Text = _defaultValue;
    lblPrompt.Text = _formPrompt;
    frmInputDialog.Text = _formCaption;

    // Retrieve the working rectangle from the Screen class
    // using the PrimaryScreen and the WorkingArea properties.
    System.Drawing.Rectangle workingRectangle = 
         Screen.PrimaryScreen.WorkingArea;

    if((_xPos >= 0 && _xPos < workingRectangle.Width) && 
         (_yPos >= 0 && _yPos < workingRectangle.Height))
    {
        frmInputDialog.StartPosition = FormStartPosition.Manual;
        frmInputDialog.Location = new System.Drawing.Point(_xPos, _yPos);
    }
    else
     {  
        // InputBox in the center if not specifier or out of screen size
        frmInputDialog.StartPosition = 
            FormStartPosition.CenterScreen; 
     }

    string PrompText = lblPrompt.Text;

    int n = 0;
    int Index = 0;
    // Counting the new line in the Prompt string
    while(PrompText.IndexOf("\n",Index) > -1)            
    {
        Index = PrompText.IndexOf("\n",Index)+1;
        n++;
    }

    if( n == 0 )
        n = 1;

    // Down here making the form bigger.
    System.Drawing.Point Txt = txtInput.Location; 
    Txt.Y = Txt.Y + (n*4);
    txtInput.Location = Txt; 
    System.Drawing.Size form = frmInputDialog.Size; 
    form.Height = form.Height + (n*4);
    frmInputDialog.Size = form; 

    txtInput.SelectionStart = 0;
    txtInput.SelectionLength = txtInput.Text.Length;
    txtInput.Focus();
}

Conclusion

The InputBox a simple static class which you can use in Windows Forms application to prompt for a text. It can also be used from Visual Basic .NET when you compile it in a library and refer this library from your VB project.

If we will make our own MessageBox, then we have to make in the same way as we made the InputBox. Then we will support other languages with our own MessageBox.

Have fun!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

hestol
Software Developer (Senior) Cyber Com Consulting A/S
Denmark Denmark
Member
I have working with C since 1988, and updates to VC++ in 1998. The first software I was making in VC++ was Fan calculation program with graph. This Fan Was integrated with the Oracle system.
I've been working almost exclusively with C# and .NET since
beginning of the technology.
Now I am working with SOA structure, MVC 3.0, SQL Server 2008 and VS.NET 2010. The company Cyber Com Consulting A/S is a IT consult house.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionchecking for the blank inputmemberJayakishor.r10 Jan '13 - 22:42 
I am checking for the blank input when the OK key is pressed. If it is blank then I bring up a messagebox stating the error.
When I close the message box the Inputbox closes.
I don't want the inputbox to close.
I want the user to reenter the text without having to reopen the inputbox.
 
How to acheive it.
 
Jayakishor
QuestionPossible Enhancement.memberMember 372800416 Jun '12 - 19:17 
This is a beautiful piece of code. A possible addition to it would be to check for Keypress events on the input box and perform a button ok click on enter key.
 
You can do it as follow:
 
txtInput.KeyPress += new KeyPressEventHandler(CheckKeys);  //Bind the keyevent handler to the textbox.
 
and then just handle the keyevents like such.
 
static private void CheckKeys(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)13)
    {
        btnOK.PerformClick();
    }
}

AnswerRe: Possible Enhancement.memberClifford Nelson26 Jun '12 - 13:54 
Even easier:
 
txtInput.KeyPress += (s, e) =>
{
    if (e.KeyChar == (char) 13)
        btnOK.PerformClick();
};

QuestionPasswordChar functionalitymemberMember 791674021 Dec '11 - 2:38 
Hi, I just downloaded your code, and thought i might post a small change i made regarding the PasswordChar property:
#region Public Static Show functions
 
static public InputBoxResult Show(string Prompt, char PwdChar)
{
    InitializeComponent();
    FormPrompt = Prompt;
    txtInput.PasswordChar = PwdChar;
 
    // Display the form as a modal dialog box.
    LoadForm();
    frmInputDialog.ShowDialog();
    return OutputResponse;
}
 
static public InputBoxResult Show(string Prompt,string Title, char PwdChar)
{
    InitializeComponent();
 
    FormCaption = Title;
    FormPrompt = Prompt;
 
    txtInput.PasswordChar = PwdChar;
 
    // Display the form as a modal dialog box.
    LoadForm();
    frmInputDialog.ShowDialog();
    return OutputResponse;
}
 
static public InputBoxResult Show(string Prompt,string Title,string Default, char PwdChar)
{
    InitializeComponent();
 
    FormCaption = Title;
    FormPrompt = Prompt;
    DefaultValue = Default;
    txtInput.PasswordChar = PwdChar;
 
    // Display the form as a modal dialog box.
    LoadForm();
    frmInputDialog.ShowDialog();
    return OutputResponse;
}
 
static public InputBoxResult Show(string Prompt,string Title,string Default,int XPos,int YPos, char PwdChar)
{
    InitializeComponent();
    FormCaption = Title;
    FormPrompt = Prompt;
    DefaultValue = Default;
    XPosition = XPos;
    YPosition = YPos;
    txtInput.PasswordChar = PwdChar;
 
    // Display the form as a modal dialog box.
    LoadForm();
    frmInputDialog.ShowDialog();
    return OutputResponse;
}
 
#endregion
 
This way, you can add a Password Char if you want your textbox to receive input in that manner, the call for the methods should include the password char or a null value, if you dont want to use it.
 
Example 1:
InputBoxResult C = InputBox.Show("Type the new password", "Title", '*');
 
Example 2:
InputBoxResult C = InputBox.Show("Type the new name", "Title", null);
 
Hope it helps;
GeneralMy vote of 5memberMember 791674021 Dec '11 - 2:34 
Nice and useful code
GeneralImprovement suggestionsmemberMario Majcica29 Mar '11 - 22:55 
Hi hestol,
 
thanks for this handy class.
I would like to suggest adding this two lines of code:
 
frmInputDialog.AcceptButton = btnOK;
frmInputDialog.CancelButton = btnCancel;
 
and perhaps for comodity, even if not a good practice, set the namespace to
 
namespace System.Windows.Forms
 
Can be useful?
 
Bye
GeneralRe: Improvement suggestionsmemberhestol7 Apr '11 - 1:57 
Thx
Big Grin | :-D
BugRe: Improvement suggestionsmemberClifford Nelson26 Jun '12 - 13:57 
How about updating the code???
NewsInputBox in C++memberMember 371636021 Jan '11 - 4:53 
Hello, Hestol!
 
I've modified your code to C++ and I could be realized if you take a look on it: http://paste.pocoo.org/show/324387/
 
Thank you!
GeneralMy vote of 5memberCon Fuse16 Nov '10 - 2:05 
Worked Perfectly for what I wanted to do! And so easy to use and understand.
GeneralThank youmemberAvi Farah15 Nov '10 - 10:25 
You have written a useful article that inspired a conversation--Thank you.
--Avi Farah
AnswerNice Inteligent Solution (Just flamed the other guy for that VB hack rubish).memberDavePaterson11 Sep '10 - 10:32 
Just though you might like these as methods as well. (Sorry I really like the TRY pattern).
 
static public bool TryGet(string Prompt, out String Output)
{
InputBoxResult result = Show(Prompt);
 
Output = result.Text;
 
return (result.ReturnCode == DialogResult.OK);
 
}
 
static public bool TryGet(string Prompt, string Title, out String Output)
{
InputBoxResult result = Show(Prompt,Title);
 
Output = result.Text;
 
return (result.ReturnCode == DialogResult.OK);
 
}
 
static public bool TryGet(string Prompt, string Title, string Default, out String Output)
{
InputBoxResult result = Show(Prompt, Title,Default);
 
Output = result.Text;
 
return (result.ReturnCode == DialogResult.OK);
 
}
 
static public bool TryGet(string Prompt, string Title, string Default, int XPos, int YPos, out String Output)
{
InputBoxResult result = Show(Prompt, Title, Default,XPos,YPos);
 
Output = result.Text;
 
return (result.ReturnCode == DialogResult.OK);
 
}
 
Thanks hestol Cool | :cool:
AnswerRe: Nice Inteligent Solution (Just flamed the other guy for that VB hack rubish).memberhestol13 Sep '10 - 3:19 
thx Smile | :)
GeneralInputBoxmemberJoeNovak6910 Nov '09 - 9:52 
I am checking for the correct input when the OK key is pressed. If is is not then I bring up a messagebox stating the error.
When I close the message box the Inputbox closes.
I don't want the inputbox to close.
I want the user to reenter the text without having to reopen the inputbox.
 
Here's my code sample:
static private void btnOK_Click(object sender, System.EventArgs e)
{
if (txtInput.Text = "Correct Data")
{
OutputResponse.ReturnCode = DialogResult.OK;
OutputResponse.Text = txtInput.Text;
frmInputDialog.Dispose();
}
else
{
MessageBox.Show("Please enter valid data", "MyTitle", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtInput.Text = string.Empty;
}
}
QuestionRe: InputBoxmemberJayakishor.r10 Jan '13 - 0:24 
I too have the same issue. Did you get eny idea how to reenter the text without having to reopen the inputbox.
GeneralJavier DazamemberJavier Daza19 Sep '09 - 3:00 
Excelente era justo lo que buscaba Muchas Gracias
Generalno need for thismembereagles81212 Sep '07 - 23:52 
it is possible to use VB inputbox by using namespaces etc...
u dont have to do this unless u want to add something more.
try calling vb codes, there are some several helpfull things,
like inputbox.
GeneralRe: no need for thismemberJordanwb31 Mar '08 - 13:02 
What if you don't like VB(Like me)?
GeneralRe: no need for thismemberbhains17 Jul '08 - 9:43 
string str1;
 
str1 = Microsoft.VisualBasic.Interaction.InputBox("Please enter your name","your Name","",100,100);
 
/*
 
you can call inputbox in c# as shown above
 

..As simple as that..
 

/*
GeneralRe: no need for thismemberhestol31 Jul '08 - 20:37 
Thanks ! Big Grin | :-D
GeneralRe: no need for thismemberRiz Thon14 Sep '08 - 22:20 
You don't necessarily want to point to Microsoft.VisualBasic (the dll may not be here for some reason, you may not want to load that dll for just a tiny simple form, it might be better not to use old things that are kept mostly for backward compatibility).
But if you don't care about linking to it, then yup it works like a charm!
GeneralRe: Good Onemembermanas25 Sep '08 - 4:29 
Nice oye .
 
Manas Patnaik
www.vectorexpert.com

AnswerRe: no need for thismemberClifford Nelson26 Jun '12 - 14:02 
Totally agree. Not much code for what need to do, and this way can customize when customer tells you he does not like the retro look.
GeneralIt was useful to mememberPaul Reynolds15 Oct '09 - 9:05 
It was useful to me because I wanted to pre-process the input text, converting tab and CRLF delimiters to commas. The VisualBasic InputBox does not allow additional custom functionality to be added.
AnswerRe: It was useful to mememberhestol15 Oct '09 - 21:43 
Big Grin | :-D
Thx
GeneralRe: It was useful to mememberClifford Nelson26 Jun '12 - 14:03 
Yes it can be useful there also.
GeneralRe: no need for thismemberMidax23 Apr '10 - 6:30 
Great job! Thumbs Up | :thumbsup:
Smile | :)
Tkx
.

GeneralProblems with this codememberDavid Piepgrass3 May '05 - 14:30 
Sorry, bud, this just isn't a very good implementation. Some problems with it:
 
- It doesn't necessarily resize properly to accommodate large Prompt strings because it calculates the size of the message incorrectly.
- It does something Really Weird in my application: whenever this InputBox is closed, my entire application disappears from the screen for a split second!
- The OK button is not the default button, so the Enter key doesn't work.
- The Cancel button is not marked as such, so the Escape key doesn't work.
- It uses all static variables, which means that if, for any reason, your application attempts to put two of these babies on the screen at once, bad things will happen.
- Why the heck does it use flat buttons?
- The mechanism by which results are returned (an "InputBoxResult" structure) thing is relatively cumbersome to use.

GeneralRe: Problems with this codememberDavid Piepgrass3 May '05 - 14:36 
So I made my own version:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
 
namespace System.Windows.Forms
{
	/// <summary>
	/// This static class contains methods named Show() to display a dialog box 
	/// with an input field, similar in appearance to the one in Visual Basic.
	/// The Show() method returns null if the user clicks Cancel, and non-null
	/// if the user clicks OK.
	/// </summary>
	public class InputBox
	{
		static public string Show(string Prompt) 
			{ return Show(Prompt, null, null, int.MinValue, int.MinValue); }
		static public string Show(string Prompt, string Title, string Default)
			{ return Show(Prompt, Title, Default, int.MinValue, int.MinValue); }
		
		static public string Show(string Prompt, string Title, string Default, int xPos, int yPos)
		{
			if (Title == null)
				Title = Application.ProductName;
			InputBoxDialog dlg = new InputBoxDialog(Prompt, Title, xPos, yPos);
			if (Default != null)
				dlg.txtInput.Text = Default;
			DialogResult result = dlg.ShowDialog();
			if (result == DialogResult.Cancel)
				return null;
			else
				return dlg.txtInput.Text;
		}
	}
 
	internal class InputBoxDialog : Form 
	{
		private System.Windows.Forms.Label lblPrompt;
		public System.Windows.Forms.TextBox txtInput;
		private System.Windows.Forms.Button btnOK;
		private System.Windows.Forms.Button btnCancel;
	
		public InputBoxDialog(string prompt, string title) : this(prompt, title, int.MinValue, int.MinValue) {} 
 
 		public InputBoxDialog(string prompt, string title, int xPos, int yPos)
		{
			if (xPos != int.MinValue && yPos != int.MinValue) {
				this.StartPosition = FormStartPosition.Manual;
				this.Location = new System.Drawing.Point(xPos, yPos);
			}
 
			InitializeComponent();
 
			lblPrompt.Text = prompt;
			this.Text = title;
 
			Graphics g = this.CreateGraphics();
			SizeF size = g.MeasureString(prompt, lblPrompt.Font, lblPrompt.Width);
			Debug.WriteLine("PROMPT SIZE: " + size);
			if (size.Height > lblPrompt.Height)
				this.Height += (int)size.Height - lblPrompt.Height;
 
			txtInput.SelectionStart = 0;
			txtInput.SelectionLength = txtInput.Text.Length;
			txtInput.Focus();
		}
 
		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.lblPrompt = new System.Windows.Forms.Label();
			this.txtInput = new System.Windows.Forms.TextBox();
			this.btnOK = new System.Windows.Forms.Button();
			this.btnCancel = new System.Windows.Forms.Button();
			this.SuspendLayout();
			// 
			// lblPrompt
			// 
			this.lblPrompt.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left)));
			this.lblPrompt.BackColor = System.Drawing.SystemColors.Control;
			this.lblPrompt.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.lblPrompt.Location = new System.Drawing.Point(12, 9);
			this.lblPrompt.Name = "lblPrompt";
			this.lblPrompt.Size = new System.Drawing.Size(302, 71);
			this.lblPrompt.TabIndex = 3;
			// 
			// txtInput
			// 
			this.txtInput.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
			this.txtInput.Location = new System.Drawing.Point(8, 88);
			this.txtInput.Name = "txtInput";
			this.txtInput.Size = new System.Drawing.Size(381, 20);
			this.txtInput.TabIndex = 0;
			this.txtInput.Text = "";
			// 
			// btnOK
			// 
			this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
			this.btnOK.Location = new System.Drawing.Point(326, 8);
			this.btnOK.Name = "btnOK";
			this.btnOK.Size = new System.Drawing.Size(64, 24);
			this.btnOK.TabIndex = 1;
			this.btnOK.Text = "&OK";
			// 
			// btnCancel
			// 
			this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.btnCancel.Location = new System.Drawing.Point(326, 40);
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.Size = new System.Drawing.Size(64, 24);
			this.btnCancel.TabIndex = 2;
			this.btnCancel.Text = "&Cancel";
			// 
			// InputBoxDialog
			// 
			this.AcceptButton = this.btnOK;
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.CancelButton = this.btnCancel;
			this.ClientSize = new System.Drawing.Size(398, 117);
			this.Controls.Add(this.txtInput);
			this.Controls.Add(this.btnCancel);
			this.Controls.Add(this.btnOK);
			this.Controls.Add(this.lblPrompt);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "InputBoxDialog";
			this.ResumeLayout(false);
 
		}
		#endregion
	}
}

GeneralRe: Problems with this codememberhestol3 May '05 - 21:20 

Big Grin | :-D
Yours code is a very good solution. But you miss the check for that the Input box not starts outside from the screen. I have often set the input box to a position on the screen, and some time the end user have a smaller screen than mine so therefore that check. See the code:
 

public InputBoxDialog(string prompt, string title, int xPos, int yPos)
{
// Retrieve the working rectangle from the Screen class
// using the PrimaryScreen and the WorkingArea properties.
System.Drawing.Rectangle workingRectangle = Screen.PrimaryScreen.WorkingArea;
 
if((xPos >= 0 && xPos < workingRectangle.Width-100) && (yPos >= 0 && yPos < workingRectangle.Height-100))
{
this.StartPosition = FormStartPosition.Manual;
this.Location = new System.Drawing.Point(xPos, yPos);
}
else
this.StartPosition = FormStartPosition.CenterScreen;
 
}
 

GeneralRe: Problems with this codememberDavid Piepgrass4 May '05 - 14:16 
Hmm. Well, I took that out 'cause I don't think it works properly if you have multiple monitors (which I do). It'll move your InputBox from a perfectly valid position on the second monitor to the primary monitor.
 
Somebody should write a "MoveOntoScreen" method that makes sure a window is within the boundaries of any one of the installed monitors....
GeneralRe: Problems with this code [modified]memberBajotumn.com15 Sep '09 - 16:39 
Here's that function for you. Plenty of methods for customization.
        public static bool MoveFormOntoScreen(System.Windows.Forms.Form pForm) {
            bool tFormLocationTest = CheckFormIsInScreenBounds(pForm);
            if (!tFormLocationTest) {
                pForm.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
                pForm.Location = FormCenterLocation(pForm, System.Windows.Forms.Screen.PrimaryScreen);
            }
            return tFormLocationTest;
        }
 
        public static bool CheckFormIsInScreenBounds(System.Windows.Forms.Form pForm) {
            return FormIsOnAScreen(pForm.Bounds);
        }
 
        public static bool FormIsOnAScreen(System.Drawing.Rectangle pRect) {
            bool tPointInScreen = false;
            foreach (System.Windows.Forms.Screen tScr in System.Windows.Forms.Screen.AllScreens) {
                if (!tPointInScreen) {
                    tPointInScreen = tScr.Bounds.Contains(pRect);
                }
 
                Debug.WriteLine(pRect + " in screen " + tScr.WorkingArea + " = " + tPointInScreen);
            }
            return tPointInScreen;
        }
 
        public static System.Drawing.Point FormCenterLocation(System.Windows.Forms.Form pForm, System.Windows.Forms.Screen pScreen) {
            int x = pScreen.WorkingArea.Right - pScreen.WorkingArea.Width / 2 - pForm.Width / 2;
            int y = pScreen.WorkingArea.Bottom - pScreen.WorkingArea.Height / 2 - pForm.Height / 2;
            return new Point(x, y);
        }

 
modified on Tuesday, September 15, 2009 11:21 PM

AnswerRe: Problems with this codememberhestol15 Sep '09 - 21:38 
Big Grin | :-D Thanks!
I was looking for a function to check how many screen the user have!
Now I got it! Wink | ;) Thumbs Up | :thumbsup:
AnswerRe: Problems with this codememberClifford Nelson26 Jun '12 - 14:15 
I have one big problem with your solution, and that is how to determine if the user has canceled. There are cases where the user wants to enter an empty string. I would tend to go with an out parameter, and return the dialog result so it can be used in an if statement.

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 21 Apr 2005
Article Copyright 2005 by hestol
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid