Friday, May 05, 2006

Creating a New Folder dialog in C#

I am building a File Manager that may look like Total Commander in C# so I had to implement a New Folder dialog that should be as simple to use as possible...This Is what It looks like:

So...The functionality should be like this...The user enters the new folder name...and clicks Ok if he is ok with what he entered..or Cancel if he changed his mind. Also the user has the possibility to press Enter to accept the text and Esc to cancel...

First Add two buttons to the form and name one OkButton and the other CancelButton,then add a textBox and name it FolderName....if you want....you can add a label that displays the text New Folder but if you do not add it it won`t change any functionality of the dialog.

Now set the Dialog Result of the OK button to OK and the Dialog Result of the Cancel button to Cancel into the Form`s Load event handler. The code should look like this:

this.OkButton.DialogResult = DialogResult.OK;
this.CancelButton.DialogResult = DialogResult.Cancel

Next....set the TextBox`s name proprieties and assign a new event that should handle the Esc and Enter keyPress. So here is the code:

private void FolderName_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
this.OkButton.PerformClick();
}
if (e.KeyCode == Keys.Enter)
{
this.CancelButton.PerformClick();
}
}

In order to make the code simple we just "press" the Ok and Cancel through code using the PerformClick() method.

Another improvement would be: when the dialog opens the focus should be on the TextBox and not on something else...so one line of code should solve that:

this.FolderName.Focus();

No comments: