Several tips for C # Programming

Source: Internet
Author: User

1. Minimize the window

When you click "X" or "Alt + F4", the window is minimized,
For example:
Protected override void WndProc (ref Message m)
{
Const int WM_SYSCOMMAND = 0 ×0112;
Const int SC _CLOSE = 0xF060;
If (m. Msg = WM_SYSCOMMAND & (int) m. WParam = SC _CLOSE)
{
// User clicked close button
This. WindowState = FormWindowState. Minimized;
Return;
}
Base. WndProc (ref m );
}

Ii. How to Make the Foreach loop run faster
Foreach is a ready-made statement for simple enumeration and processing of elements in a set. Its usage is as follows:
Using System;
Using System. Collections;
Namespace LoopTest
{
Class Class1
{
Static void Main (string [] args)
{
// Create an ArrayList of strings
ArrayList array = new ArrayList ();
Array. Add ("Marty ");
Array. Add ("Bill ");
Array. Add ("George ");
// Print the value of every item
Foreach (string item in array)
{
Console. WriteLine (item );
}
}
}
You can use the foreach statement in each set that implements the Ienumerable interface. For more information about foreach usage, see C # Language Specification in. NET Framework SDK documentation.

During compilation, the C # editor converts each foreach area. IEnumerator enumerator = array. GetEnumerator ();
Try
{
String item;
While (enumerator. MoveNext ())
{
Item = (string) enumerator. Current;
Console. WriteLine (item );
}
}
Finally
{
IDisposable d = enumerator as IDisposable;
If (d! = Null) d. Dispose ();
}
This indicates that in the background, foreach management will bring additional code to your program that increases system overhead.

3. Save the image to an XML file
In the WinForm resource file, convert the Image attributes and other non-text content of PictureBox into text for saving. This is achieved through Serialization,
Example ://
Using System. Runtime. Serialization. Formatters. Soap;
Stream stream = new FileStream ("E: \ Image. xml", FileMode. Create, FileAccess. Write, FileShare. None );
SoapFormatter f = new SoapFormatter ();
Image img = Image. FromFile ("E: \ Image.bmp ");
F. Serialize (stream, img );
Stream. Close ();

4. Shielding CTRL-V
The TextBox Control in WinForm has no way to block the clipboard pasting action for the CTRL-V. If you need an input box but do not want the user to paste the clipboard content, you can use the RichTextBox Control instead, and shield the CTRL-V key in KeyDown, for example:

Private void richTextBox1_KeyDown (object sender, System. Windows. Forms. KeyEventArgs e)
{
If (e. Control & e. KeyCode = Keys. V)
E. Handled = true;
}

1. Determine whether a file or folder exists
To use System. IO. File, it is very easy to check whether a File exists:
Bool exist = System. IO. File. Exists (fileName );

To determine whether a Directory (folder) exists, you can use System. IO. Directory:
Bool exist = System. IO. Directory. Exists (folderName );

Ii. Use the delegate type to design custom events
In C # programming, except Method and Property, any Class can have its own Event ). To define and use a Custom Event, follow these steps:
(1) define a delegate type outside the Class to determine the interface of the Event program
(2) declare a public event variable within the Class, whose type is the delegate type defined in the previous step.
(3) trigger an event somewhere inside a Method or Property
(4) use the + = Operator to specify the event handler in the Client program

Example: // define the Delegate type and constrain the parameters of the Event program
Public delegate void MyEventHandler (object sender, long lineNumber );

Public class DataImports
{
// Define the new event NewLineRead
Public event MyEventHandler NewLineRead;

Public void ImportData ()
{
Long I = 0; // event Parameter
While ()
{
I ++;
// Trigger the event
If (NewLineRead! = Null) NewLineRead (this, I );
//...
}
//...
}
//...
}

// The following is the Client code

Private void CallMethod ()
{
// Declare the Class variable without WithEvents
Private DataImports _ da = null;
// Specify the event handler
_ Da. NewLineRead + = new MyEventHandler (this. DA_EnterNewLine );
// Call the Class method. An event is triggered on the way.
_ Da. ImportData ();
}
// Event handler
Private void DA_EnterNewLine (object sender, long lineNumber)
{
//...
}

Iii. IP address and host name resolution
System. Net can be used to achieve IP resolution similar to Ping command line, for example, to resolve the host name to an IP address or vice versa: private string GetHostNameByIP (string ipAddress)
{
IPHostEntry hostInfo = Dns. GetHostByAddress (ipAddress );
Return hostInfo. HostName;
}
Private string GetIPByHostName (string hostName)
{
System. Net. IPHostEntry hostInfo = Dns. GetHostByName (hostName );
Return hostInfo. AddressList [0]. ToString ();
}

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.