15-03-16 WinForm

Source: Internet
Author: User

WinForm application is an intelligent client technology, we can use the WinForm application to help us obtain information or transfer information, etc. it is the CS interactive mode software, requires our computer must be installed
Client software;

Wisdom does not drag the control is not refers to WinForm, refers to the time when ASP.

Do site drag control will generate a lot of code, those code is useless for you, when a site all things are dragged out, then there will be a lot of garbage code, when the site is running, the garbage code
will also be executed, so the more controls you drag, the lower the performance of the site; When you make a website, everything is knocked out by 1.1, not by the drag control, but WinForm can only drag the control.

One technique for winformui is called WPF, and the language it uses is XAML.

Either the form application or the console application main function is the main entry;

In Program.cs
Static Class Program
{
static void Main ()
{
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (FALSE);
Application.Run (New Form1 ()); Creates an Form1 object that is invisible to the console-created objects, but the objects created by WinForm are visible;
}
}


public partial class Form1:form
{
Public Form1 ()
{
Initialcomponent ();
}
}
The cube is the icon of the method, the Blue box is the field icon, the enumeration icon is two small yellow squares, the property is a small board
private void InitializeComponent ()
{
This. SuspendLayout ();
//
//
//
A whole bunch of Form1 properties
}
Form1.Designer.cs automatically generated code for the form;
Form1.resx form Application resource files, music pictures of these,
Form1 Background Code
Form1 and Form1.Designer.cs all have partial Form1 classes they collectively form the Form1 class
How to quickly switch to the foreground in the background, right-click in the background, point to the first view of the designer
Each of the controls seen in the WinForm is actually each type; the upper bracket control is the process of creating the object of the class;

When we close the form, we execute the method of releasing the resource.
Private System.ComponentModel.IContainer component = NULL;
protected override void Dispose (bool disposing)
{
if (disposing&& (component! = NULL))
{
Components. Dispose ();
}
Base. Dispose (disposing);
}

Setting properties for a control can be set in the code inside the Form1.Designer.cs, either by selecting the control, right-clicking, property, or F4 exporting the property bar, F5 running, F6 generating the solution;
2. Properties
Name: In the background to get the foreground control object, you need to use the Name property;
BackgroundImageLayout: The control's background picture fills the control completely;
ContextMenuStrip: Right-click menu; To add a right-click menu, Find the Toolbox, menu and toolbar, ContextMenuStrip drag it over, display it at the bottom of the form, and set it in the top left corner.
The Contxetmenustrip in the properties of this control are bound together;
Cursor: pointer type; move to the set control;
Enable indicates whether the control is available,
Visiable Indicates whether the control is visible;

3. Events
Something happened;
Register Event: The property above the LEI mark is the event, the control inside the selected events are our most commonly used events; in the corresponding event name, double-click to register the event, the event is essentially a method;
The MessageBox.Show () in the WinForm is the Console.WriteLine () inside the console;
Trigger event:

Two parameters of the event method: The first argument, the object sender, that represents the objects that triggered the event, who triggered the event, and the second parameter is EventArgs e, which indicates the resources required to execute the event;
Object sender indicates that these classes in the control still inherit from the object class
We write WinForm applications are accumulated by various events;
In the project directory, right-click, add, you can add multiple form forms; The
Form object created in the main function, which we call the main form of the form application; The
also means that when you close the main form, the entire application is closed;
If you want to register a control with its default selected event, you can simply double-click the control.
From2 frm2 = new Form2 ();
Frm2.show ();
How to get the main form object in another form;
to create a new class;
public static class test //Static classes in the entire project resource sharing, static classes can not create objects, we say static class data sharing, so we save some shared data inside;
{
   public static FORM1 _frm1test; declare a static field;
} The
then throws the main form object into the _frm1test while the program is running;
in the WinForm application; If you want to close all applications, you have to close the main form, but the main form object is not available in the Form3 form, because it is not in a class; now to get the object of the main form in FORM3
, we pass it through the static class. In fact, it is passed through a static field, in FORM3 although the object inside the Form1 is not accessible, but I can access the test static class, because in a project
can also access the public field in test;
We're going to put the object in when the program is running, so just write
Test._frm1test = This in the Form_Load event.
Write
Test._frm1test.close () in FORM3;
In fact, by building the role of the middle bridge, static classes in the static field is the middle bridge;

MouseEnter event; The event triggered by the mouse entering the control;
This. Close (); Close the current form;
This. Width is the size of the form and is a dead value;
This. Clientsize.width is the width of the current form, and he becomes larger as the form pulls larger;
This. Height
This. Clientsize.height
Button1. Location = coordinates of the new point (R.next (0,x+1), R.next (0,y+1)) button;
Drag out a control if there is a small arrow, then click to see;

Textbox
Multiline property If True, you can display multiple lines
WordWrap property If True, the line can be wrapped automatically;
ScrollBars Property scroll bar, Landscape, portrait, bidirectional
All the properties through the mouse settings, can be set through the background code;
PasswordChar Let the text box display a single character
The default event is TextChanged

The same thing is done many times to use the Toolbox, the timer in the component, the default enable is False. Interval the frequency of the event execution, in milliseconds;
There is only one event tick
A marquee is a string intercept (substring) the first character is intercepted and executed repeatedly in a timer;
The label event is displayed as Lbltme.text = DateTime.Now.Tostring (), but at the beginning of the second it will not move, because the timer is started after one second, in order to
solve this problem, when the form is loaded, Assign the time of the current system to my label   Lbltme.text = DateTime.Now.Tostring (); one written in the clock event
One is written in the Form_Load event;
DateTime.Now.Hour
DateTime.Now.Minute
DateTime.Now.Second
SoundPlayer sp = new SoundPlayer ();//Create a music object to play
[email protected] ""//the path of the playback file, only. wav files can be played;
Sp.play ();                   Playback
can control different permissions through the Visible property, different users see the interface;
Textbox1.clear (); Empty text box;
Textbox1.focus (); The text box gets the focus;
the true and false of a property can be controlled by a button;
if (button1. Text = = "Wrap line")
{
  textbox1.wordwrap = false;
  Button1. Text = = "Cancel Automatic line-wrapping";
}
Else if
{
  textbox1.wordwrap = true;
  Button1. Text = = "Wrap line";
}

The checkbox indicates that the control is not selected, and that both radio and multi-Select
How to group the control, this time need to use the container groupbox, put 2 RadioButton put in, and then put into a group;
By default in a form, all radio buttons allow only one selection and can be grouped using GroupBox;
MDI form, a parent form contains many subforms, and these subforms do not move out of the parent form;
MDI Form Design
1, first determine a parent form; Find the form's properties IsMdiContainer set to True is the parent form.
Menu is the toolbox under the menu and the tool bar MenuStrip, to the inside of the button registration event directly double-click the corresponding button;
2, create the subform, and set their parent form;
Form2 frm2 = new Form2 ();
Frm2. MdiParent = this;
Frm2.show ();
Sub-forms are arranged horizontally in an MDI form
LayoutMDI (layoutmdi.tilehorizontal);
The subform is arranged vertically in an MDI form
LayoutMDI (layoutmdi.tilevertical);

PictureBox controls that display pictures
The Sizemode:stretchimage property displays the picture in the picture frame in full;
Picturebox.image = Image.FromFile (@ "Dizhi");
The class for manipulating files is file, and the class of action path is path, and the class for manipulating folders is directory
Gets the full path of all files for the specified folder
string[] Path = directory.getfiles (@ "path");
Sets how the picture displays PictureBox1 in PictureBox. SizeMode = Pictureboxsizemode.stretchimage;
FileStream cannot read a file such as word.excel; read such a file to use the other class libraries provided by. NET;

----------------------------------------------------------------------------------------------

Create folder Directory.CreateDirectory (@ "path name");
Delete Folder Directory.delete (@ "path name"); if there is something in the folder, then delete the Recycle Bin is not, is a completely deleted operation;
Delete Folder Directory.delete (@ "path name", true); even if there is something inside, it can be deleted; Recycle Bin is not, is a completely deleted operation;
Cut Folder Directory.move ("Original Path", "New Path");
Locate the folder under. jpg end of file string[] path = directory.getfiles (@ "path", "*.jpg");
string[] path = Directory.getdirectories (); Get the path to all folders under folder
Directory.Exists ("path"), whether this folder exists;
Browser Control WebBrowser control, many form applications can open Web pages, with the Webbrower main property is the URL,
string text = TextBox1.Text;
Uri uri = new Uri ("http://" +text);
Webbrower1.url = URI;
ComboBox.items.Add ("Zhang San"); Add content to Combox; The added type is object;
ComboBox.items.AddRange (); Add a collection;
Combobox.items.Clear (); clear the set;
DropDownStyle: Controls the style of the drop-down box
When the name of the ComboBox, it is generally cbo+ ...
The default event for the ComboBox is the Selectindexchanged event;
In order to prevent continuous addition, the original should be emptied before adding;
To get the value of the ComboBox, use Cbomonth. Selecteditem.tostring (); SelectedText and SelectedValue are not taking
Str.split (New char[]{' Month '},stringsplitoptions. Removeemptyentries);
((year%400==0) | | (year%4==0&&year%100!=0)) Determine the conditions of a leap year;

Listbox1.items.Add ()//Add elements to the listbox;
Path.getfilename ();//Get the file name in the path
in the ListBox common event DoubleClick
ListBox. SelectedIndex the index of the currently selected item;
to write a part of the code to be reused as a method, select the code you want, right-click, refactor, extract method, write Method name
dialog box, just create a dialog object, open the dialog box OpenFileDialog, Save dialog box SaveFileDialog, Font dialog fontdialog, Color dialog box ColorDialog
OpenFileDialog ofd = new OpenFileDialog ();
Ofd. title = "123";//Set the caption of the dialog box;
Ofd. MultiSelect = true; The settings dialog can be selected more than once;
Ofd. InitialDirectory = @ "... The path of the desktop ";//Setup dialog opens the initial interface;
Ofd. Filter = "text file |*.txt| all files |*.*"; Show the type of file you want to see;
Ofd.showdialog;//Set properties must be set in front of the dialog box, otherwise it will not be used;
String path = Ofd. FileName; Gets the path to the file selected in the Open dialog box;
string[] Path = ofd. FileNames;
using (FileStream fsrread = new FileStream (path,filemode.openorcreate,fileaccess.read))
{
  byte[] Buffer = new BYTE[1024*1024*5];
  int r = Fsrread.read (Buffer,0,buffer. Length); The number of bytes actually read;
  TextBox1.Text = Encoding.Default.GetString (buffer,0,r);
}

SaveFileDialog sfd= new SaveFileDialog ();
SfD. ShowDialog ();
SfD. Title
SfD. InitialDirectory
SfD. Filter
String path = sfd. filename;//obtain the path;
using (FileStream fswrite = new FileStream (path,filemode.openorcreate,fileaccess.write))
{
byte[] buffer = Encoding.Default.GetBytes (TextBox1.Text);
Fswrite.write (buffer,0,buffer,length);
}

FontDialog fd = new FontDialog ();
Fd. ShowDialog ();
Textbox1.font = FD. Font;


ColorDialog cd = new ColorDialog ();
Cd. ShowDialog ();
Textbox1.forecolor = CD. Color;

Toolbox, container, Panel
Panel.visiable = false; The controls in the Panel also disappeared;
Toolbox, menus and toolbars have MenuStrip is the menu bar;
String FileName = Path.getfilename (Path); Get the file name in the path with the path class
..... Toolstripmenuitem.text = = ""; Get the text of the menu bar
Processes can be understood as each application is a process;. NET operation process is the class
process[] Pros = process.getprocesses (); The class name. The method name calls this static method, getting all the processes that the computer is running, returning an array of process types;
Process Pro = new process ();
Pro.kill (); close the process;
Procsee.start ("Calc"); Turn on the computer through the process;
Procsee.start ("MSPaint");
Procsee.start ("notepad");
Procsee.start ("IExplore", "www.baidu.com");
Open the specified file through the process;
Processes Pro = new process ();//Create a Progress object;
ProcessInfo psi = new ProcessInfo (@ "file path"); Create the cause of the p.start when you need this type of object;
Pro. StartInfo = PSI;
P.start ();
Each process is made up of multiple threads;
Single-threaded to bring us problems;
WinForm to see the output in the Debugging, window, the output can be opened;
In VS, each time a program is run, the computer assigns a main thread (only one) to execute such a program.
Drag the form, the action form is the main thread is doing, if the main thread to do other things, then the form will appear suspended animation;
The class for the action thread in VS is thread
Create a Thread object
Thread th = new Thread (Test);//Pass in a method (delegate) that allows the thread to execute; This is a thread, but not the main path;
private void Test ()
{
for (int i = 0;i < 10000;i++)
{
Console.WriteLine (i);
}
}
Th.start ()//Mark this thread is ready, can be executed at any time, thread execution is determined by the CPU, we cannot call the thread manually;
Call method takes one thread?
There are 2 threads, one is foreground thread and one is background thread;
Foreground thread: Only all foreground threads are closed to complete the program shutdown;
Background thread: As long as all the foreground threads end, the background thread automatically ends;
The threads we create ourselves by default are foreground threads;
The main thread also belongs to the foreground threads
Set the thread to foreground thread th. IsBackground = true;
The disadvantage of single thread;
1. If the program to do a lot of programs, there will be suspended animation of the state; The purpose of multithreading is to allow the program to do more things;
The controls in the main form and form are created by the main thread,
Thread th = new Thread (Test);
private void Test ()
{
for (int i = 0;i < 10000;i++)
{
TextBox1.Text = i; If this is changed, because TextBox1 is the main thread created, and th is our new thread, there is a new thread to access the main threads of resources, under the. NETFramework is not allowed to cross-thread access;
}
}
Th.start ()
In the execution of the above code, if you close the program during the run, there may be an error, the error is to release resources error, because the main thread off, causing the text box to disappear, the new thread is not finished, but there is no text box, no access,
So the error;
The workaround is to determine if the new thread is null in the FormClosing event, and if it is null, it is closed, and if it is not NULL, turn it off;
if (th = null)
{
Th. Abort ();//end this thread, and when the thread is finished, it cannot start;
}
Contral.checkforillegalcrossthreadcalls = false; Cancel Check cross-thread access, written in Formload event
The control class is the base class for all WinForm controls;
Thread.Sleep (1000) A static method that allows the current thread to stop running for a period of time; 1000 for 1000 milliseconds;
Name Thread Name
Thread.CurrentThread gets the current thread reference;
We can't manipulate the CPU through code.

string[] Path = ofd. FileNames; Get all the files in the Open box;
Add multiple selected files to the list box;
for (int i = 0; i < path.length;i++)
{
ListBox1. Items.Add (Path.getfilename (path[i));
}
Click to play the next song
int index = ListBox1. SelectedIndex;
index++;
if (index = = ListBox1. Items.Count)
{
index = 0;
}
ListBox1. SelectedIndex = Index; This sentence is critical, you must copy the new index to ListBox1. SelectedIndex; otherwise the index is unchanged;
Thread is divided into foreground thread and background thread, we should use background thread;
Thread th = new Thread (Test);
private void Test (string s)
{
for (int i = 0;i < 10000;i++)
{
Console.WriteLine (i);
}
}
Procedure error, the reason is as follows;
If a thread executes a method that requires parameters, the parameter must be of type object;
Thread th = new Thread (Test);
Th. IsBackground = true;
Th. Start ("123");

private void Test (object s)
{
for (int i = 0;i < 10000;i++)
{
Console.WriteLine (i);
}
}
So there will be no mistakes;

Wave-winning machine
Outside
BOOL B = false;

private void PlayGame ()
{
Random r = new Random ();
while (b)
{
Label1. Text = R.next (0,10). ToString ();
Label2. Text = R.next (0,10). ToString ();
Label3. Text = R.next (0,10). ToString ();
}
}
In the button click event:
if (b = = false)
{
B = true;
Button1.Text = "Stop";
Thread th = new Thread (PlayGame);
Th.background = true;
Th.start ();
}
Else
{
b = false;
Button1.Text = "Start";
}

In the Formload event:
Contral.checkforillegalcrossthreadcalls = false;

AVG = convert.todouble (avg. ToString ("0.00")); True retention of two bits, the original value changed
Console.WriteLine ("{0:0.00}", avg), the output of the time to retain two bits, the original value has not changed;

The

is sorted in ascending order by bubbling the array of integers {1, 3, 5, 7, 90, 2, 4, 6, 8, 10}
int[] nums = {1, 3, 5, 7,, 2, 4, 6, 8, ten};
for (int i = 0;i < nums.length-1;i++)
{
    for (int j = 0; J < nums.length-1-i;j++)
&NBSP ;       {
           if (nums[ J] > Nums[j+1])
            {
                int temp = nums[j];
               Nums[j] = nums[j+1];
               nums[j+1] = temp;   
           }
         }
}
The fastest ascending array.sort (nums);
Descending   Array.reverse (nums);


while (Index! =-1)
{
i++;
index = str. IndexOf ("cough", index + 1);
if (index = =-1)
{
Break
}
Console.WriteLine ("{1}", "I, index" where the cough occurred at {0} times);

Search for a word in a string that appears several times in that position of the key method;

Hello World! "
string[] snew = str. Split (New char[]{'},stringsplitoptions.removeemptyentries);
String strnew = String.Join ("", snew);

string s = "";
string ss = "";
These two are not a thing, the above is empty, the following is not empty, there is a space string;


The Reverse () method is
for (int i = 0, i<str.length/2,i++)
{
int temp = Str[i];
Str[i] = str[str.length-1-i];
Str[str.length-1-i] = temp;
}

If you want to rewrite a method, mark it as virtual, or abstract, and the ordinary method cannot be rewritten;


private string name;
public string Name
{
get {return name;}
set {name = value;}
}

public string Name
{
Get
Set
}

The following is an automatic attribute, the same effect as above;

15-03-16 WinForm

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.