C # modal forms

Source: Internet
Author: User

Summary: This article describes how to use modal forms in Windows program development based on the. NET platform. Some content is extended to the application of general forms.
Overview
What is a modal form? It can be simply understood as a form dialog box. You must complete the operation on the form or close the form before returning the form to open the form. This article does not discuss the definition, features, and functions of modal forms in detail, but mainly focuses on how to apply them.. Net form application effectively uses modal forms to solve common problems encountered in using modal forms.

  Modal form attribute settings
In.. net. windows. forms. the Form class represents a form. You can directly add a form through the Visual Studio 2005 designer and switch to the design mode. The properties and events of the form are displayed in the Properties window. Take the option dialog box opened by the menu tool> Option of Visual Studio 2005 program as an example. You still need to set the format initialized by the designer to be professional. Fortunately, these settings can all be implemented through attribute settings in the designer mode. The author will use the code to implement the corresponding functions and describe them in detail.

  • Form. startposition attribute to determine the position when the form appears for the first time. It is set to display in the middle of the parent form. This. startposition = formstartposition. centerparent;
  • Form. helpbutton attribute to determine whether the "help" button is in the Form title bar. Set display, which looks more user-friendly, but does not necessarily implement the help function. This. helpbutton = true;
  • Form. maximizebox attribute to determine whether there is a maximize box in the upper right corner of the Form title bar. Set to not display her. This. maximizebox = false;
  • Form. minimizebox attribute, and determine whether there is a minimization box in the upper right corner of the Form title bar. Set to prevent display. This. minimizebox = false;
  • Form. showicon attribute, indicating whether to display the icon in the Form title bar. The settings are not displayed. This. showicon = false;
  • Form. showintaskbar attribute to determine whether the form appears in the Windows taskbar. Of course, this will save valuable space on the taskbar. This. showintaskbar = false;
  • Form. formborderstyle attribute, indicating the appearance and behavior of the border and title bar of the form. Setting this attribute will not allow you to drag and adjust the size of the form. This. formborderstyle = formborderstyle. fixedsingle;
  • Form. controlbox attribute to determine whether the form has a "control/system" menu box. You can use this setting to hide the control button of the title bar. In some cases, it is necessary to set it to false so that there will be no control buttons in the title bar. This. controlbox = false;

By setting the above attributes, the static function of the modal form is basically implemented. You can determine whether to adjust the size of the form based on the actual situation.

  Button in the modal form
In a modal form (for example, the "option" dialog box in Visual Studio 2005), there are two basic buttons: one [OK] button for submission and the other [cancel] button for uncommitting, sometimes a [application] button is added. However, the "about" form in the "help" menu may have only one [OK] button.

Windows Forms provide good support for user friendliness. The acceptbutton and cancelbutton attributes can be found in the attribute settings of the form design interface. The default value is null, indicating that the acceptbutton and cancelbutton attributes are displayed (none ). In properties, you can set the value by selecting the button on the form. The code generated by modifying the property is as follows. Two buttons are defined first:

Private system. Windows. Forms. Button buttonok;
Private system. Windows. Forms. Button buttoncancel;

"Accept" button of the form: If this button is set, each time you press "enter", the button is equivalent to "click. "Cancel" button of the form: If this button is set, each time you press the "ESC" key, it is equivalent to "click.

This. acceptbutton = This. buttonok;

This. cancelbutton = This. buttoncancel;

It can be seen that you can use shortcut keys to easily access specific buttons, but there are some exceptions,For example, if the focus of the form is on buttoncancel, when you press {enter}, the actually pressed key will be buttoncancel rather than buttonok. If the focus is on the third button, the {enter} press is equivalent to clicking this button.. Another detail is that the behavior of clicking the button with the mouse and the shortcut key operation button is different. The shortcut key operation button does not display the Display Effect of the button being pressed, and it seems that nothing has happened.

 

  Opening and Closing of modal forms
When it comes to opening a modal form, we generally use form. the showdialog () method or an overloaded form. showdialog (iwin32window). The last method displays the form as a modal dialog box with the specified owner. The following code shows,

Optionform form = new optionform ();
// Form. showdialog ();
Form. showdialog (this );

For a modal form opened in the specified owner mode, you can obtain the reference of the main form within the form,

// Access the corresponding form within the modal form
Mainform form = This. owner as mainform;

NOTE: If it is opened in form. showdialog () mode, the form. Owner attribute will be blank reference.

When talking about the closure of the modal form, let's take a look at the return value after the form is closed. Whether you call the form. showdialog () method or form. showdialog (iwin32window) method, the system. Windows. Forms. dialogresult enumeration value is returned when the form is closed. Refer to msdn. The enumerated values are as follows:

  • Dialogresult. Abort. the return value of the dialog box is abort (usually sent from the "Abort" button ).
  • Dialogresult. Cancel. the return value of the dialog box is cancel (usually sent from the button labeled "cancel ).
  • Dialogresult. Ignore. the return value of the dialog box is ignore (usually sent from the button labeled "Ignore ).
  • Dialogresult. No. The return value of the dialog box is no (usually sent from the "no" button ).
  • Dialogresult. None, which returns nothing from the dialog box. This indicates that the dialog box continues to run.
  • Dialogresult. OK. the return value of the dialog box is OK (usually sent from the button labeled "OK ).
  • Dialogresult. Retry. the return value of the dialog box is retry (usually sent from the button labeled "retry ).
  • Dialogresult. Yes. The return value of the dialog box is yes (usually sent from the button labeled "yes ).

For some reason, in actual user operations, for example, the option data cannot be saved and the input setting data is incorrect. Click the [OK] button to prevent the form from being closed to adjust the input settings. I don't think the code that some developers post in the technical community to block form close is very good. The following code describes the implementation. Note that three events are used:

// Register the form close event
This. formclosing + = new system. Windows. Forms. formclosingeventhandler (this. optionform_formclosing );

// Register the confirm button event
This. buttonok. Click + = new system. eventhandler (this. buttonok_click );
// Register the cancel button event
This. buttoncancel. Click + = new system. eventhandler (this. buttoncancel_click );
The event handler corresponding to the three events is as follows,
// Confirm the button Handler
Private void buttonok_click (Object sender, eventargs E)
{
// Assume that textboxpath is used to record the directory path. If no directory path exists, you must reset it.
If (this. textboxpath. Text. Trim (). Length = 0)
{
MessageBox. Show ("the input path is incorrect! ");
This. textboxpath. Focus ();
}
Else
{
This. dialogresult = dialogresult. OK;
}
}
// Cancel the button Handler
Private void buttoncancel_click (Object sender, eventargs E)
{
This. dialogresult = dialogresult. Cancel;
}
// Close the form handler, which occurs when the form is closed.
Private void optionform_formclosing (Object sender, formclosingeventargs E)
{
If (this. dialogresult! = Dialogresult. Cancel & this. dialogresult! = Dialogresult. OK)

E. Cancel = true;
}

The above code is normal, that is, the event is too much to write, modify the above Code, remove the [cancel] button event and form close event and related event handler. First, you must set the dialogresult attribute of the button in the form constructor to return a specific dialogresult.

This. buttonok. dialogresult = system. Windows. Forms. dialogresult. OK;

This. buttoncancel. dialogresult = system. Windows. Forms. dialogresult. Cancel;

Register the confirm button event,

// Register the confirm button event
This. buttonok. Click + = new system. eventhandler (this. buttonok_click );
// Confirm the button Handler
Private void buttonok_click (Object sender, eventargs E)
{
If (this. textboxpath. Text. Trim (). Length = 0)
{
MessageBox. Show ("the entered path is incorrect! ");
This. textboxpath. Focus ();
// Set the text box focus
This. dialogresult = dialogresult. None;
}
}

It can be seen that the code of the new implementation method is halved.

 

In addition, you can disable or remove the close button by using windowsapi.

First add using system. runtime. interopservices;

Then write the following code into the project to disable the close button.

Private const int SC _close = 0xf060;
Private const int mf_enabled = 0x00000000;
Private const int mf_grayed = 0x00000001;
Private const int mf_disabled = 0x00000002;
[Dllimport ("user32.dll", entrypoint = "getsystemmenu")]
Private Static extern intptr getsystemmenu (intptr hwnd, int brevert );
[Dllimport ("user32.dll")]
Public static extern bool enablemenuitem (intptr hmenu, int uidenableitem, int uenable );

Write the following code in the page_load event of page loading.

Intptr hmenu = getsystemmenu (this. Handle, 0 );
Enablemenuitem (hmenu, SC _close, mf_disabled | mf_grayed );

 

Remove close button

[Dllimport ("user32.dll")]
Private Static extern int removemenu (INT hmenu, int nposition, int wflags );

/// <Summary>
/// Return value. If the value is not zero, the operation is successful. If the value is zero, the operation fails.
/// </Summary>
/// <Param name = "ihwnd"> handle of the window </param>
/// <Returns> Successful </returns>
Private int removexbutton (INT ihwnd)
{
Int isysmenu;
Const int mf_bycommand = 0x400; // 0x400-Disable
Isysmenu = getsystemmenu (this. Handle. toint32 (), 0 );
Return removemenu (isysmenu, 6, mf_bycommand );
}

 

  Modal forms provided by. NET Framework
. NET Framework provides some commonly used dialog boxes, saving a lot of trouble during the development process. We will introduce them below.
MessageBox. Displays message boxes that contain text, buttons, and symbols (notifications and instructions. Use the MessageBox. Show static method to open the dialog box.

Public static dialogresult show (string text );

This method contains multiple overloaded versions. A complicated method is as follows,

Public static dialogresult show (iwin32window owner, string text, string caption, messageboxbuttons buttons, messageboxicon icon, messageboxdefaultbutton defaultbutton, messageboxoptions options, string helpfilepath, helpnavigator Navigator,
Object PARAM );

You can customize the dialog box based on different parameters.

 

Some other dialog boxes provide specific functions.

  • Openfiledialog. The open file dialog box inherits from the filedialog class and prompts the user to open the file. This class cannot be inherited. It is common to open files.
  • Savefiledialog. The Save file dialog box inherits from the filedialog class and prompts you to select the file storage location. This class cannot be inherited.
  • Folderbrowserdialog. The directory browsing dialog box inherits from the commondialog class and prompts you to select a folder. This class cannot be inherited.
  • Fontdialog. The font Setting Dialog Box inherits from the commondialog class, prompting you to select a font from the font installed on your local computer. This class can be inherited.
  • Colordialog. The color Setting dialog box, inherited from the commondialog class, represents a general dialog box that displays available colors and controls that allow users to define custom colors. This class can be inherited.
  • Pagesetupdialog. The print page Setting Dialog Box inherits from the commondialog class and allows you to change the page-related printing settings, including margins and paper directions. This class cannot be inherited.
  • Printdialog. The Print dialog box inherits from the commondialog class. You can select a printer and select the part to be printed in the document. This class cannot be inherited.
  • Printpreviewdialog. Print the preview dialog box, inherited from the form class, indicating the dialog box containing printpreviewcontrol. This class can be inherited. Because this class inherits from the form class

    Printpreviewdialog. showdialog ();
    Printpreviewdialog. showdialog (iwin32window );
    You can also use printpreviewdialog. Show (); or use printpreviewdialog. Show (iwin32window) to enable mode opening in normal mode.

The file dialog box abstraction base class filedialog is inherited from the commondialog abstract class. Therefore, all the dialogs inherited from this class can be inherited through commondialog. showdialog (); or its heavy commondialog. showdialog (iwin32window); The method opens the form in modal mode.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.