. Net winform Study Notes

Source: Internet
Author: User
1, MDI form

There are two forms, frmmain and frmchild. Then:
Frmmain: Set the ismdicontainer attribute to true.
Open the subwindow:
Write the following code in related events:
Frmchild child = new frmchild ();
Child. mdiparent = This; // This indicates that the current form is its parent form.
Child. Show ();
When opening a subform, if only one subform is allowed, you can add the following judgment:
If (this. activemdichild! = NULL)
{
This. activemdichild. Close (); // close the opened subform.
//....
}
Change the background of the MDI main form
Declare a form object first
Private system. Windows. Forms. mdiclient m_mdiclient;
In form_load and other events, add the following code:
Int icnt = This. Controls. count;
For (INT I = 0; I <icnt; I ++)
{
If (this. controls [I]. GetType (). tostring () = "system. Windows. Forms. mdiclient ")
{
This. m_mdiclient = (system. Windows. Forms. mdiclient) This. controls [I];
Break;
}
}
This. m_mdiclient.backcolor = system. Drawing. color. Silver;
See http://cnblogs.com/Daview/archive/2004/05/06/8381.aspx for details

2. Create a system tray menu
2.1 create a contextmenu (cmnmain) menu
2.2. Add a policyicon component and set the contextmenu attribute to cmnmain.
2.3, corresponding form change event (minimized)
Private void frmmain_sizechanged (Object sender, eventargs E)
{
If (this. windowstate = formwindowstate. Minimized)
{
This. Hide ();
Noimain. Visible = true;
}
}

2.4. Click the contextmenu event on the system tray.
Private void mniopen (Object sender, eventargs E)
{
Noimain. Visible = false;
This. Show ();
This. Focus ();
}

2.5. Respond to the user double-click System Tray Icon event
Private void noimain_doubleclick (Object S, eventargs E)
{
Minopen. javasmclick (); // The same as the Click Event of the mniopen button
}
** Add the corresponding event handle **

3. Create an irregular form
3.1. Create an irregular image on the form, which can be drawn using GDI + or be filled with images on the image control.
3.2, set the form's backcolor to colora, and then set transparencykey to colora
3.3, set formborderstyle to none;

4. Create the top form
This. topmost = true; // set topmost of the form to true.

5. Call external programs

Using system. Diagnostics

Process proc = new process ();
Proc. startinfo. filename = @ "notepad.exe"; // note the path
Proc. startinfo. Arguments = "";
Proc. Start ();

// Obtain the current directory. getcurrentdirectory () (using system. Io)

6. Use of Toolbar
The Toolbar Control usually needs to be used in combination with the imagelist control (the icon must be used)
In response to the toolbar, click the event handler code:
Switch (toolbarname. Buttons. indexof (E. Button ))
{
Case 0: // The first button
// Code...
Break;
Case 1: // the second button
// Code...
Break;
// Other case code
Default: // it is processed by default.
// Code...
Break;
}

7. the dialog box appears to obtain the relevant return values.
Run the following code in the form closing event to ask when the user closes the form.
Dialogresult result = MessageBox. Show (this, "Do you really want to close this window? "," Close prompt ", messageboxbuttons. okcancel, messageboxicon. Question );
If (result = dialogresult. OK)
{
// Close the window
E. Cancel = false;
}
Else
{
// Cancel closing
E. Cancel = true;
}

8. Print controls
Requires at least two controls
Printdocument
Printpreviewdialog: In the preview dialog box, you must use printdocument to set the document attribute
Corresponding printdocument
Printpage event (print or preview event handler) Code of printdocument, required.

Float fltheight = 0;
Float fltlineperpage = 0;
Long lngtopmargin = E. marginbounds. Top;
Int intcount = 0;
String strline;

// Calculate the number of lines per page to determine when to change pages
Fltlineperpage = E. marginbounds. Height/txtprinttext. Font. getheight (E. Graphics );


While (strline = streamtoprint. Readline ())! = NULL) & (intcount <fltlineperpage ))
{
Intcount + = 1;
Fltheight = lngtopmargin + (intcount * txtprinttext. Font. getheight (E. Graphics ));
E. Graphics. drawstring (strline, txtprinttext. Font, brushes. Green, E. marginbounds. Left, fltheight, new stringformat ());
}

// Determine whether to change pages
If (strline! = NULL)
{
E. hasmorepages = true;
}
Else
{
E. hasmorepages = false;
}
The streamtoprint of the above Code must be declared as a form-level variable:
Private system. Io. stringreader streamtoprint;

Code for opening the preview dialog box (do not write it in the printpage event)
Streamtoprint = new system. Io. stringreader (txtprinttext. Text );
Printpreviewdialogname. showdialog ();

9. String object nature and stringbuilder class. Use string
A String object is an unchangeable type. When we modify a String object, a New String object is generated.
Therefore, we recommend that you use the stringbuilder class when changing character objects frequently:
[Sample Code] construct a query string
Stringbuilder sb = new stringbuilder ("");
SB. append ("select * from employees where ");
SB. append ("ID = {0} and ");
SB. append ("Title = '{1 }'");
String cmd = sb. tostring ();

SB = NULL; // clear it when it is no longer needed

Cmd = string. Format (CMD, txtid. Text, txttile. Text); // fill the format item with the actual value

Judge whether the string is null:
Check whether a string is null or not a basic programming requirement. A valid method is to use the Length attribute of the string class to replace null or compare it.

Comparison string: Use the string. Equals method to compare two strings
String str1 = "yourtext ";
If (str1.equals ("teststing "))
{
// Do something
}

10. Determine whether a string is in another string (array ).
Several methods required
String. Split (char); // split by char, returns a String Array
Array. indexof (array, string): returns the subscript of the first matching item of the specified string in the array.
Array. lastindexof (array, string): returns the subscript of the last matching item of the specified string in the array.
If no match exists,-1 is returned.
[Sample Code]:
String strnum= "001,003,005,008 ";
String [] strarray = strnum. Split (','); // split by commas (,). Split the string into Char or char arrays.
 
Console. writeline (array. indexof (strarray, "004"). tostring ());

11. DataGrid ing between DataGrid and tables and columns
After the data is read from the database and bound to the DataGrid, the column header of the DataGrid is usually the same as the field name of the database. If
If you do not want this, you can use the ing technology of tables and columns:
Using system. Data. Common;

String strsql = "select * from department ";
Oledbdataadapter adapter = new oledbdataadapter (strsql, Conn );

Datatablemapping dtmdep = Adapter. tablemappings. Add ("department", "department table ");

Dtmdep. columnmappings. Add ("dep_id", "department ID ");
Dtmdep. columnmappings. Add ("dep_name", "department name ");

Dataset DS = new dataset ();

Adapter. Fill (DS, "Department"); // The "department table" cannot be used here"

Response to the Click Event (currentcellchanged event of the DataGrid)
Datagridname. currentcell. columnnumber; // subscript of the column to be clicked, starting from 0, the same below
Datagridname. currentcell. rownumber; // subscript of the row to be clicked
Datagridname [datagridname. currentcell]; // The value of the row and column to be clicked

Datagridname [maid. currentrowindex, N]. tostring (); // obtain the value of column N + 1 of the clicked row.

12. dynamically Add a menu and add a response event to it
Add top menu:
Mainmenuname. menuitems. Add ("top-level menu 1"); // each added one will be automatically placed behind

Add sub menu:
Menuitem mniitemn = new menuitem ("menuitemtext ")
Menuitem mniitemn = new menuitem ("menuitemtext", new eventhandler (eventdealname ))
Mainmenuname. menuitems [N]. menuitems. Add (mniitemn); // n is the top-level menu subscript to be added, starting from 0

After creating the menu, add the event:
Mniitemn. Click + = new eventhandler (eventdealname );

You can also add an event while adding a menu:
Menuitem mniitemn = new menuitem ("menuitemtext", new eventhandler (eventdealname ));
Mainmenuname. menuitems [N]. menuitems. Add (mniitemn );

13. Simple Application of Regular Expressions (matching, replacement, and splitting)
Using system. Text. regularexpressions;

// Matching example
String strregextext = "your number is: 020-32234102 ";
String filter = @ "/d {3}-/D *";

RegEx = new RegEx (filter );
Match match = RegEx. Match (strregextext );

If (match. Success) // determines whether a match exists.
{
Console. writeline ("length of the Match:" + match. length. tostring ());
Console. writeline ("matching string:" + match. tostring ());
Console. writeline ("match the first character subscript in the original string:" + match. Index. tostring ());
}
 
// Example of replacement
String replacedtext = RegEx. Replace (strregextext, "020-88888888 ");
Console. writeline (replacedtext); // output "your number is 020-88888888"

// Example of splitting
String strsplittext = "A 020-32654 020-35648 Bing 020-365984 ";
Foreach (string s in RegEx. Split (strsplittext ))
{
Console. writeline (s); // output "A, B" in turn"
}

13. Simple multi-thread programming
Using system. Threading;

Thread threadtest = new thread (New threadstart (threadcompute ));
Threadtest. Start (); // use another thread running method threadcompute
 
Threadcompute method prototype:
Private void threadcompute ()
{}

14. Operate the Registry
Using system. diagnostics;
Using Microsoft. Win32;
// Operate the Registry
Registrykey regkey = registry. localmachine. opensubkey ("software", true );

// Add a subkey and add a key-value pair to it
Registrykey newkey = regkey. createsubkey ("regnewkey ");
Newkey. setvalue ("keyname1", "keyvalue1 ");
Newkey. setvalue ("keyname2", "keyvalue2 ");

// Obtain the newly added value
MessageBox. Show (newkey. getvalue ("keyname1"). tostring ());

// Delete a key value (pair)
Newkey. deletevalue ("keyname1 ");

// Delete the entire subkey
Regkey. deletesubkey ("regnewkey ");

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.