May 25, 2010

Creating a C# Form Dialog

Creating a windows form in C# that acts similarly to the built-in dialogs is pretty straightforward. However, it isn’t immediately obvious how to do it and there are some rather convoluted suggestions out there in the world wild web, so I thought I’d document my approach.

Start by creating a normal form. Add the buttons that will return the DialogResult to the user. In the properties pane set the DialogResult property for these buttons appropriately. There is a drop down list that shows all the standard dialog result enumerated choices. You’ll also want to select the form and consider setting the following properties:

  1. FormBorderStyle:Fixed Dialog
  2. MinimizeBox:False
  3. MaximizeBox:False
  4. ControlBox:False
  5. Topmost:True – However, this keeps the dialog on top of ALL other windows, which may not be what you want.
  6. ShowIcon:False – Also sets ShowInTaskbar to false – I actually like to leave this true and topmost set to false. That way the dialog can’t get “hidden” if the user switches to another program but the user has a way to get back to it from the task bar.
  7. CancelButton: the button you want to act like Cancel (often duplicative of the DialogResult set earlier – I believe this has to do with default cancel keystroke
  8. StartPosition: CenterParent

Now you new up this form and show it with the ShowDialog() method instead of the Show() method. Using ShowDialog allows it to return a DialogResult just like the built in dialogs.

MyNewDialog the_dialog = new MyNewDialog();


DialogResult result = the_dialog.ShowDialog();
if (result == DialogResult.OK) //If you set a button to return OK
{
DoTheOkThing();
}

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.