C # learning notes 4 Windows Forms applications

Source: Internet
Author: User

A form is a visual interface for interaction between a program and a user. A form class defines a template for generating a form, and a form is generated when a form class is instantiated.

The Form class defined in the system. Windows. Forms namespace Of the. NET Framework class library is the base class of all form classes.

1. common attributes

Properties: You can set the icon, title, position, and background on the form attribute panel, or implement the code.

(1) Name attribute: used to obtain or set the name of a form. In an application, the name attribute can be used to reference a form.
(2) windowstate attribute: used to obtain or set the window state of a form. There are three types of values: normal (normal display of the form), minimized (display of the Form in minimal form), and maximized (display of the Form in maximum form ).
(3) startposition attribute: used to obtain or set the start position of the form during running.
(4) text attribute: This attribute is a string attribute used to set or return the text displayed in the title bar of the window.
(5)Acceptbutton attributes: This attribute is used to obtain or set a value. This value is the name of a button. When you press enter, it is equivalent to clicking the button on the form.
(6)Cancelbutton attributes: This attribute is used to obtain or set a value. This value is the name of a button. When you press the ESC key, it is equivalent to clicking the button on the form.
(7)Modal attributes: This attribute is used to set whether the form is a formatted display form. If the form is displayed in mode, the attribute value is true; otherwise, the value is false. When the form is displayed in a mode, only objects in the mode form can be input. The format must be hidden or closed (usually in response to a user operation) before another form can be input. A format with mode display is usually used as a dialog box in the application.
(8)Activecontrol attributes: Used to obtain or set the active controls in the container control. A form is also a container control.
(9) activemdichild attribute: used to obtain the current active subwindow of the Multi-Document Interface (MDI.
(10) autoscroll attribute: used to obtain or set a value that indicates whether the form is automatically rolled. If this property value is set to true, a scroll bar is displayed on the form when any control is located outside the work zone of the form. In addition, when automatic scrolling is enabled, the workspace of the form is automatically rolled to make the control with the input focus visible.
(11) enabled attribute: used to obtain or set a value that indicates whether the control can respond to user interaction. If the control can respond to user interaction, the value is true; otherwise, the value is false. The default value is true.
(12) keypreview attribute: used to obtain or set a value that indicates whether the form will receive the event before passing the key event to the control with focus. If the value is true, the form receives the button event. If the value is false, the form does not receive the button event.
(13)Showintaskbar attributes: Used to obtain or set a value indicating whether to display a form in the Windows taskbar.
(14) visible attribute: used to obtain or set a value that indicates whether the form or control is displayed. If the value is true, a form or control is displayed. If the value is false, a form or control is not displayed.
(15) Capture property: If this property value is true, the mouse is limited to the response of this control, regardless of whether the mouse is within the control range.
2. Common Methods

Own form this. Hide ();

Other Forms

Form2 F2 = new form2 ();
F2.show ();

The following describes the most common methods for forms.
(1) show method: This method is used to display the form. The call format is:
Form name. Show ();
The form name is the name of the form to be displayed.
(2) Hide method: This method is used to hide the form. The call format is as follows:
Form name. Hide ();
The form name is the name of the form to be hidden.
(3) Refresh method: This method is used to refresh and redraw the form. The call format is:
Form name. Refresh ();
The form name is the name of the form to be refreshed.
(4) Activate method: This method activates the form and gives it focus. The call format is:
Form name. Activate ();
The form name is the name of the form to be activated.
(5) Close method: This method is used to close the form. The call format is:
Form name. Close ();
The form name is the name of the form to be closed.
(6) showdialog method: This method is used to display the form as a mode dialog box. The call format is:
Form name. showdialog ();

 

3. Common events

Add events for forms and controls in the "events" tab of the property panel.

(1) Load event: This event occurs when the form is loaded to the memory, that is, before the first display of the form.
(2) activated event: This event occurs when the form is activated.
(3) deactivate event: This event occurs when the form loses focus and becomes inactive.
(4) resize event: This event occurs when the form size is changed.
(5) paint event: This event occurs when the form is repainted.
(6) Click Event: This event occurs when the user clicks the form.
(7) DoubleClick event: This event occurs when you double-click a form.
(8) closed event: This event occurs when the form is closed.

 

4. Add events

Take the form load event as an example:

The load event occurs when the form is loaded. The configuration steps are as follows.
(1) Open vs2008, create a Windows form application, and name it formeventtest.
(2) Open the form1 attribute window and switch to the "event" tab (a lightning flag)
(3) locate the load event item and double-click it to enter the Event code editing file form1.cs to write code for it.

Private void mainform_load (Object sender, eventargs e) {If (MessageBox. show ("I am text: view form 2", "I am title", messageboxbuttons. yesnocancel, messageboxicon. question) = dialogresult. yes) {form2 F2 = new form2 (); f2.show () ;}} private void mainform_formclosing (Object sender, formclosingeventargs e) {dialogresult DR = MessageBox. show ("Close Window", "prompt", messageboxbuttons. yesno, messageboxicon. warning); If (DR = dialogresult. yes) {e. cancel = false;} else {e. cancel = true ;}}

As a matter of fact, similar to VB, double-clicking on the form will open the load event to edit the code.

 

5. inherit the form

An inherited form is to create a new form based on the structure of the existing form. This process of inheriting from the existing form is called visual inheritance.

Two ways to create an inherited form

Programming Method:

Inheritance selector:

 

6. Controls

Forms are composed of controls, which are divided into common controls and advanced controls. common controls include text controls, selection controls, and group controls.

C # The control base class is the control class in the namespace of system. Windows. forms.

Text controls: Label, button, Textbox, and RichTextBox

Select class controls: checkbox, ComboBox, ListBox, and radiobutton

Group controls: groupbox, panel, flowlayoutpanel, splitcontainer, tabcontrol, tablelayoutpanel

 

C # control Overview:

Describes the attributes, methods, and events of multiple common controls.

 

7. Special implementation

(1) Start the welcome page

Set this interface to the welcome interface and add the timer control. The main interface will be started after several seconds of Countdown

 

(2) set the startup form for a multi-form application

In program. CS, change the parameters of the run method.

Public static void run (from mainfrom );

Example: application. Run (New form1 ());

Where form1 is the form name

 

(3) Exit the program

Form-related events

This. Hide (); // hide

This. Show (); Display

This. Close (); close. Note that the entire application will be closed.

Application. Exit (); close. Note that the entire application will be closed.

 

(4) "accept" and "cancel" buttons

Private void form1_load (Object sender, eventargs e) {This. acceptbutton = button1; // set it to "accept". The enter key is equivalent to clicking this button. cancelbutton = button2; // set it to the "cancel" button. The ESC key is equivalent to clicking this button}

(5) Start the browser to open the webpage

System. Diagnostics. process. Start (E. linktext); // Replace E. linktext with a specific link.

 

(6) determine whether a string is Numeric

Int;
If (int32.tryparse (textbox1.text, out ))
{
// MessageBox. Show ("Number ");
}
Else
{
MessageBox. Show ("non-digit ");
}

 

8. textbox

Password text box: Set the passwordchar attribute of the text box or the usesystempasswordchar attribute.

Multi-line text box: Set the multiline attribute to true.

Highlighted: Set the selecttionstart and selectionlength attributes.

 

9. RichTextBox

A formatted text control is provided for explicit, input, and operation of formatted text, for example, the explicit font, color, Link, loading text from a file, and embedded graphics are implemented, and repeated editing operations and string searching are revoked.

Private void form1_load (Object sender, eventargs e) {This. acceptbutton = button1; // set it to "accept". The enter key is equivalent to clicking this button. cancelbutton = button2; // set it to "cancel". The ESC key is equivalent to clicking this button richtextbox1.scrollbars = richtextboxscrollbars. vertical; // only the explicit vertical scroll bar richtextbox1.selectionfont = new font ("", 12, fontstyle. bold); // font size, bold richtextbox1.selectioncolor = system. drawing. color. blue; // font color blue richtextbox1.text = "Welcome to http://www.cumt.edu.cn mining"; // set text, automatically add hyperlink richtextbox1.selectionbullet = true; // The control content is arranged in the format of the Project symbol list. richtextbox1.selectionindent = 8; // the left edge is located at richtextbox1.selectionrightindent = 12; // the right edge is located at richtextbox1.savefile ("C: // Tang. rtf "); // Save the content to the file, in three formats} // RichTextBox link click Message Processing private void richtextbox‑linkclicked (Object sender, linkclickedeventargs e) {// write a link click event, start the browser to browse the system. diagnostics. process. start (E. linktext );}

 

10. drop-down ComboBox

(1) dropdownstyle: Set the style

Simple: The list is always visible.

Dropdown: Default Value, editable text box

Dropdownlist: the text box cannot be edited.

(2) select all text in the Editable box using the selectall () method

 

11 check box checkbox

Checkstate attribute: whether to select the checked and unchecked attributes.

 

12. Single-choice button

Checked property: whether to select the position true,

 

13. Value Selection Control

(1) It is used to display and input values, and provides up and down arrows. You can enter them directly or use arrows to modify values.

Maximum: Maximum Value

Mininmun: Minimum value

Value: Value

(2) Explicit format

Decimalplaces: number of digits after the decimal point. The default value is 0.

Thousandsseparater: A sub-mark. The default value is false.

Hexadecimal: hexadecimal explicit

 

14. List Control listview

(1) add and delete items: add and remove methods for the items attribute of The ListBox control

(2) currently selected project: selecteditem attribute of ListBox

(3) multiple options: selectionmode attribute

Multiextended (shift and CTRL keys are available)

Multisimple multiple choice

One: single choice

None

(4) number of items selected

Listbox1.selecteditems. Count. tostring (); multiple options

Style, column header, and column width settings

Listview1.view = view. Details; // view style,
Listview1.columns. Add ("file name"); // Add a header
Listview1.columns. Add ("path ");
Listview1.columns. Add ("size ");
Listview1.columns. Add ("Creation Time ");
Listview1.columns [0]. width = 100; // set the width.
Listview1.columns [1]. width = 200; // set the width.
Listview1.columns [2]. width = 100; // set the width.
Listview1.columns [3]. width = 100; // set the width.

 

// Add an item

Listview1.items. Clear (); // clear

Listview1.items. Add (processes [I]. processname );
Listview1.items [listview1.items. Count-1]. subitems. Add (processes [I]. Id. tostring ());

Listview1.items [listview1.items. Count-1]. subitems. Add (processes [I]. Id. tostring ());

Listview1.items [listview1.items. Count-1]. subitems. Add (processes [I]. Id. tostring ());

 

15. Grouping controls

Panel:

Groupbox: group box

Tabcontrol: Tab

(1) set the icon for the tab and change the tab title

Create a Windows application, add an imagelist control to the form, and then add a graphical list like the imagelist control;

Add a tabcontrol Control, set its imagelist attribute to the imagelist1 control, and set the imageindex attribute of the tabpage tab to the index of the corresponding image in the list.

You can directly operate on the attribute panel or write the following code:

Private void form1_load (Object sender, eventargs e) {tabcontrol1.imagelist = imagelist1; tabpage1.imageindex = 0; tabpage1.text = "Tab 1"; tabpage2.imageindex = 2; tabpage2.text = "Tab 2 ";}

 

(2) display the tab as a button

Set the appearence attribute of the tabcontrol to buttons or flatbuttons to display the tab as a button style. (3D buttons and flat buttons)

Tabcontrol1.appearance = tabappearance. Buttons;

 

(3) add controls on the tab

Private void button3_click (Object sender, eventargs e) {button btn1 = new button (); btn1.text = "Add button"; tabpage1.controls. Add (btn1 );}

 

(4) add and remove tabs

Add: The add method of the tabpages attribute

String title = "new tab" + (tabcontrol1.tabcount + 1 );
Tabpage mytabpage = new tabpage (title );
Tabcontrol1.tabpages. Add (mytabpage );

Delete: The Remove Method of the tabpages attribute

Tabcontrol1.tabpages. Remove (tabcontrol1.selectedtab );

Remove all tabs: clear of the tabpages attribute

 

(5) datagridview

The column width setting is invalid?

You must set the autosizemode attribute of the column to none to make the width setting take effect.

Center Column Title

Datagridview1.columnheadersdefaultcellstyle. Alignment = maid. middlecenter; // center the title

Center column alignment

Datagridview1.columns [0]. defaultcellstyle. Alignment = maid. middlecenter;

How can I fill all columns with the entire control?

Click the triangle in the upper-right corner of the dview-> "Edit column"-> select the last column-> the attribute box on the right has a property of "layout"-> "autosizemode, set it to fill.

Select the right row instead of a cell when selecting the datagridview.

Datagridview1.selectionmode = datagridviewselectionmode. fullrowselect; // select the positive row instead of the cell.

Assignment of the leftmost Column

Datagridview. Rows [I]. headercell. Value

Display and change width of the leftmost Column

Maid = false; // hide the leftmost Column
Datagridview1.rowheaderswidth = 60; // set the width.

Delete error prevention

Int indexid = maid. Index; // The current row
// MessageBox. Show (maid. Count. tostring () + indexid. tostring ());
If (indexid <0 | indexid> = maid. Count-1)
{}
Else
{
If (MessageBox. Show ("are you sure you want to delete it? "," Prompt ", messageboxbuttons. yesno, messageboxicon. Warning) = dialogresult. Yes)
{
Maid. Remove (maid );
}
}

Can the serial number be displayed in the fixed column on the left of the datagridview control?

(The fixed column on the left is a bit wide and has a right arrow to show the ascending sequence number for this column)

Http://topic.csdn.net/u/20100921/11/88ab1c8e-5c96-4ae0-9b73-db62af5ae16b.html

 private void dataGridView1_RowPostPaint_1(object sender, DataGridViewRowPostPaintEventArgs e)        {            Rectangle rowHeaderBounds = new Rectangle            (                 2, e.RowBounds.Top,                 this.dataGridView1.RowHeadersWidth-2, e.RowBounds.Height - 1            );            using (Brush backbrush =                new SolidBrush(SystemColors.Control))            {                e.Graphics.FillRectangle(backbrush, rowHeaderBounds);            }            if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)            {                using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))                {                    int linen = 0;                    linen = e.RowIndex + 1;                    string line = linen.ToString();                    e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);                    SolidBrush B = new SolidBrush(Color.Red);                }            }        }

 

Related Article

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.