C # basic use of Window controls and forms

Source: Internet
Author: User

Visual interfaces are usually used to interact with users, so they are a required part,

I think the visual interface under C # is better in encapsulation, and the page attributes are all placed in Form1.Designer. in the InitializeComponent () function of the cs file, the Form1.cs file calls the initialization function to perform operations on related events, such as the Click operation of the button that is frequently seen ). In the visual studio toolbox, you can drag the component and right-click the component to set its attributes.

For a simple window example, a dialog box is displayed when the window is to be closed:

Create a function in the Form1.cs file:

Private void form=formclosing (object sender, FormClosingEventArgs e) {DialogResult dr = MessageBox. Show ("Disable the form? "," Prompt ", MessageBoxButtons. yesNo, MessageBoxIcon. warning); if (dr = DialogResult. yes) {e. cancel = false;} else {e. cancel = true ;}}

In the InitializeComponent () function in the Form1.Designer. cs file, set:

This. FormClosing + = new System. Windows. Forms. FormClosingEventHandler (this. Form1_FormClosing );


this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);

The FormClosing attribute of the window is implemented by calling the Form1_FormClosing function.

You can call the Show (), Hide (), and Close () methods for the form. In addition, there are Activated and Load events that trigger the form event, which is similar to the syntax format of the FormClosing event.

Common controls and their simple settings

1. Label control:

Label1.Font = new Font ("", 12); label1.Text = "be happy if you are tired again"; label2.ForeColor = Color. Blue;

2. TextBox Control:

TextBox1.PasswordChar = '@'; // set textBox2.UseSystemPasswordChar = true according to your preferences; // set the default system password to display textBox1.ReadOnly = true; // read-only attribute textBox1.Multiline = true; // you can specify multiple rows for display.

3. RichTextBox Control: displays the font, color, Link, text loading, and image functions)

Example: open a file in button1 and open an image in button2. RichTextBox1 displays the file and image content;

Set the properties of richTextBox1:

RichTextBox1.BorderStyle = BorderStyle. Fixed3D; // set the border style richTextBox1.DetectUrls = true; // set the automatic identification hyperlink richTextBox1.ScrollBars = RichTextBoxScrollBars. Both; // set the scroll bar

Click button1 to display the open file dialog box. Select a file and then display the file content in richTextBox1:

OpenFileDialog openfile = new OpenFileDialog (); // instantiate open file dialog box openfile. filter = "rtf file (*. rtf) | *. rtf "; // sets the file filter if (openfile. showDialog () = DialogResult. OK) {richTextBox1.Clear (); // clear the text box // load the file richTextBox1.LoadFile (openfile. fileName, RichTextBoxStreamType. richText );}


Similarly, set the display image:

OpenFileDialog openpic = new OpenFileDialog (); openpic. filter = "bmp file *. bmp) | *. bmp | jpg file *. jpg) | *. jpg | ico file *. ico) | *. ico "; openpic. title = "open image"; if (openpic. showDialog () = DialogResult. OK) {Bitmap bmp = new Bitmap (openpic. fileName); // use the selected image to instantiate the Bitmap object Clipboard. setDataObject (bmp, false); // place the image in the system clipboard // determine whether the richTextBox1 control can paste the image information if (richTextBox1.CanPaste (DataFormats. getFormat (DataFormats. bitmap) richTextBox1.Paste ();}


Button control:

Button1.BackgroundImage = Properties. resources. a; button1.BackgroundImageLayout = ImageLayout. stretch; // Stretch the image button2.Image = Properties. resources. a; button2.ImageAlign = ContentAlignment. middleLeft; // sets the image alignment mode button3.FlatStyle = FlatStyle. flat; // set the appearance style of button3 button3.Text = "OK"; button4.TextAlign = ContentAlignment. middleRight; // sets the text alignment mode.


GroupBox control: A group control that displays borders and titles around the control set, but has no scroll bars)


TabControl control:

Set the appearance style of the tab:

tabControl1.Appearance = TabAppearance.Normal;

Instance: click "button1" and add a tab. "button2" removes a tab.

// Declare a string variable to generate the name of the new tab. string Title = "add tab" + (tabControl1.TabCount + 1 ). toString (); TabPage tp = new TabPage (Title); // use the add method of the tabpages attribute of the tabcontrol to add a new tab tabControl1.TabPages. add (tp );

Remove tab:

If (tabControl1.SelectedIndex = 0) {MessageBox. Show ("select the tab to Remove");} else {tabControl1.TabPages. Remove (tabControl1.SelectedTab );}


MenuStrip control menu bar -- drag the control to perform relevant settings ):

In addition, if you enter "New (& N)" in the input box, "New (N)" is displayed at run time. You can use "Alt + N" to call


ToolStrip control toolbar-there are eight different types of controls in the drop-down Bar-this control is not useful and cannot be clearly stated)

Button: contains items that can be selected from text and images;

SplitButton: adds a drop-down list based on the Button.

DropDownButton: used to select items from the drop-down list

Separator: Separator

ComboBox: displays a Combox item.

TextBox, ProgressBar, and ComboBox have similar meanings.


StatusStrip control:

It is placed at the bottom of the form to display some information about the form object.

The current system time is displayed when the form is loaded:

ToolStripStatusLabel1.Text = "current time:" + DateTime. Now. ToLongTimeString ();


ListBox control:

Instance: Use ListBox to display the list of retrieved files

Set the ListBox attribute:

ListBox1.HorizontalScrollbar = true; // horizontal listBox1.ScrollAlwaysVisible = true; // vertical listBox1.SelectionMode = SelectionMode. MultiExtended; // select multiple items in the control

Click button1 to open the file:

// Instantiate the Browse folder dialog box FolderBrowserDialog fbd = new FolderBrowserDialog (); if (fbd. showDialog () = DialogResult. OK) {// obtain the path of the selected folder textBox1.Text = fbd. selectedPath; // use the obtained folder path to instantiate the DirectoryInfo Class Object DirectoryInfo dinfo = new DirectoryInfo (textBox1.Text ); // obtain all subfolders in the specified folder and FileSystemInfo [] finfo = dinfo. getFileSystemInfos (); // Add the obtained subfolders and files to the ListBox control listBox1.Items. addRange (finfo); label2.Text = "(" + listBox1.Items. count + "item }";}

Select items in ListBox:

Private void listBox1_SelectedIndexChanged (object sender, EventArgs e) {label3.Text = "you choose:"; for (int I = 0; I <listBox1.SelectedItems. count; I ++) {label3.Text + = listBox1.SelectedItems [I] + ",";}}


ListView control: used to display list items with icons)

The instance is added to the ListView Group. You can also set the add, remove, and clear functions ):

ListView1.View = View. smallIcon; // sets the View attribute and the style. // sets two groups for listView1: listView1.Groups. add (new ListViewGroup ("name", HorizontalAlignment. left); listView1.Groups. add (new ListViewGroup ("category", HorizontalAlignment. left); listView1.Items. add ("name1"); listView1.Items. add ("name2"); listView1.Items. add ("lei1 ");

Group the items above to set their Group attributes ):

// Add listView1.Items [0]. Group = listView1.Groups [0] to the first Group; // Add listView1.Items [2]. Group = listView1.Groups [1] to the second Group;

Add item:

listView1.Items.Add(textBox1.Text.Trim());

Delete item:

listView1.Items.RemoveAt(listView1.SelectedItems[0].Index);listView1.SelectedItems.Clear();

Clear items:

listView1.Items.Clear();


TreeView control: used to display the node hierarchy)

TreeView1.ContextMenuStrip = contextMenuStrip1; // set the shortcut menu TreeNode tn = treeView1.Nodes of the tree control. add ("Root Node"); TreeNode pn1 = new TreeNode ("Node 1"); // place Node 1 to the node under the root node tn. nodes. add (pn1); TreeNode cn1 = new TreeNode ("Node 1"); pn1.Nodes. add (cn1); // expand all under the shortcut menu and fold all treeView1.ExpandAll (); treeView1.CollapseAll ();


TreeView1 is usually used with the imageList control to display nodes with images:

ImageList1.Images. add (Image. fromFile ("1.png"); imageList1.Images. add (Image. fromFile ("2.png"); treeView1.ImageList = imageList1; imageList1.ImageSize = new Size (16, 16); // 0treeView1 when the treeView1 control node icon is indexed in the imageList1 control. imageIndex = 0; // the index of the icon displayed after a node in the imageList1 control is 1treeView1. selectedImageIndex = 1;


ImageList control: used to store image resources and display them in the control to simplify image management)

ImageList1.ColorDepth = ColorDepth. Depth32Bit; // set the color depth of the image.

Attach image:

ImageList1.Images. clear (); // Clear the Image string Path = "C: \ Users \ lucky \ Desktop \ 1.jpg"; Image img = Image. fromFile (Path, true); imageList1.Images. add (img); imageList1.ImageSize = new Size (215,135); // when the image index of pictureBox1 is set, pictureBox1.Image = imageList1.Images [0] is the image index of the imageList1 control;

Clear image:

imageList1.Images.RemoveAt(0);pictureBox1.Image = null;


Common KeyUp events:

Private void txtUserName_KeyUp (object sender, KeyEventArgs e) {if (e. KeyValue = 13) // determines whether to press Enter txtUserPwd. Focus ();}


Font scrolling instance:

Private void timereffectick (object sender, EventArgs e) {// set the distance between label1 and label1.Left-= 2 between label1 and the left edge of the container's workspace; // if (label1.Right <0) {// set the distance between the left edge of label1 and the left edge of the container's workspace to label1.Left = this. width ;}}

Start rolling:

timer1.Enabled = true;


This article from "tired also happy D" blog, please be sure to keep this source http://zhangzhang.blog.51cto.com/6250085/1263395

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.