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:
- FormBorderStyle:Fixed Dialog
- Topmost:True – However, this keeps the dialog on top of ALL other windows, which may not be what you want.
- 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.
- 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
- 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