1 read the operating system and CLR version
1 operatingsystem os =2 Console.WriteLine ("Platform: {03 Console.WriteLine ("Service Pack: {04 Console.WriteLine (" Version: {0 5 Console.WriteLine ("versionstring: {06 Console.WriteLine (" CLR Version : {0
In my Windows 7 system, output the following information
6.1. 7600.0 6.1. 7600.0 4.0. 21006.1
2 read the number of CPUs, memory capacity
The required information can be read through the interface provided by Windows Management Instrumentation (WMI).
Private StaticUInt32 countphysicalprocessors () {ManagementObjectSearcher objects=Newmanagementobjectsearcher ("Select*From Win32_ComputerSystem "); Managementobjectcollection Coll=objects. Get (); foreach(ManagementObject objinchColl) { return(UInt32) obj["NumberOfProcessors"]; } return 0; } Private StaticUInt64 countphysicalmemory () {ManagementObjectSearcher objects=Newmanagementobjectsearcher ("Select*From win32_physicalmemory "); Managementobjectcollection Coll=objects. Get (); UInt64 Total=0; foreach(ManagementObject objinchColl) { Total+=(UInt64) obj["Capacity"]; } returnTotal ;}
Add a reference to assembly System.Management to ensure that your code compiles correctly.
Console.WriteLine ("Machine: {0} ", Environment.MachineName); Console.WriteLine ("# of Processors (logical): {0} ", Environment.processorcount); Console.WriteLine ("# of Processors (physical): {0} "countphysicalprocessors ()); Console.WriteLine ("RAM installed: {0: N0} bytes ", Countphysicalmemory ()); Console.WriteLine ("Is OS --bit? {0} ", Environment.is64bitoperatingsystem); Console.WriteLine ("is Process --bit? {0} ", environment.is64bitprocess); Console.WriteLine ("Little-endian: {0} ", Bitconverter.islittleendian); foreach(Screen screeninchSystem.Windows.Forms.Screen.AllScreens) {Console.WriteLine ("Screen {0} ", screen. DeviceName); Console.WriteLine ("\tprimary {0} ", screen. Primary); Console.WriteLine ("\tbounds: {0} ", screen. Bounds); Console.WriteLine ("\tworking area: {0} ", screen. Workingarea); Console.WriteLine ("\tbitsperpixel: {0} ", screen. BitsPerPixel); }
3 Reading registry key-value pairs
using (RegistryKey Keyrun = Registry.LocalMachine.OpenSubKey (@ "SOFTWARE\Microsoft\Windows\CurrentVersion\Run")) { foreach (string in keyrun.getvaluenames ()) { Console.WriteLine ("Name: {0}\tvalue: {1}", ValueName, Keyrun.getvalue ( ValueName));
Please add the namespace Microsoft.Win32 to ensure that the above code can be compiled.
4 Start, Stop the Windows service
This API provides useful functionality that is often used to manage services in an application without having to operate in the management services of the Control Panel.
New ServiceController ("e-m-POWER"); Controller. Start (); if (Controller. CanPauseAndContinue) { controller. Pause (); Controller. Continue (); }
In the. NET API, you can implement a word of installation and uninstallation services
if(args[0] ==" /I") {Managedinstallerclass.installhelper (New string[] {assembly.getexecutingassembly (). Location}); } Else if(args[0] =="/ u") {Managedinstallerclass.installhelper (New string[] {"/ u", assembly.getexecutingassembly (). Location}); }
As shown in the code, pass in the I or U parameter to the application to indicate that it is unloading or installing the program.
5 Verify if the program has strong name (P/invoke)
For example, in a program, in order to verify that the assembly has a signature, you can call the following methods
[DllImport ("Mscoree.dll", charset=CharSet.Unicode)]Static extern BOOLStrongNameSignatureVerificationEx (stringwszFilePath,BOOLFforceverification,ref BOOLpfwasverified); BOOLnotforced =false; BOOLVerified = StrongNameSignatureVerificationEx (assembly,false,refnotforced); Console.WriteLine ("verified: {0}\nforced: {1}", verified,!notforced);
This feature is commonly used in software protection methods that can be used to validate signed components. Even if your signature is removed, or if all of the assembly's signatures are removed, you can stop the program from running as long as there is a calling code in the program.
6 Responding to changes to system configuration items
For example, when we lock the system, if QQ does not exit, it will show a busy state.
Add the namespace Microsoft.Win32, and then register the following event.
Displaysettingschanged (contains changing) display settings installedfontschanged font Change palettechangedpowermodechanged power state sessionended ( User is logged out or session end) Sessionswitch (change current user) timechanged time change userpreferencechanged (user bias contains changing)
Our ERP system will monitor whether the system time changes, if the time adjusted after the ERP license file outside the scope, will cause the ERP software is not available.
7 using new features of Windows7
Windows7 system introduces some new features, such as Open File dialog, status bar can show the progress of the current task.
Newtruetrue to true
Open the dialog box in such a way that it has more OpenFileDialog functionality in the BCL's own class library. However, it is limited to Windows 7 systems, so to call this code, check the operating system version to be greater than 6, and add a reference to the assembly Windows API Code Pack for microsoft®.net framework. Please go to this address to download Http://code.msdn.microsoft.com/WindowsAPICodePack
8 checking the memory consumption of the program
Use the following method to check. Net amount of memory allocated to Programs
long available = GC. Gettotalmemory (false); Console.WriteLine ("Before allocations: {0int40000000byte newbyte= GC. Gettotalmemory (false); Console.WriteLine ("After allocations: {0
In my system, it runs the result as shown below
651,064,690,080
Use the following method to check the memory consumed by the current application
Process proc =process.getcurrentprocess (); Console.WriteLine ("Process Info:"+environment.newline+"Private Memory Size: {0: N0} "+environment.newline +"Virtual Memory Size: {1: N0} "+ Environment.NewLine +"Working Set Size: {2: N0} "+ Environment.NewLine +"Paged Memory Size: {3: N0} "+ Environment.NewLine +"Paged System Memory Size: {4: N0} "+ Environment.NewLine +"Non-paged System Memory Size: {5: N0} "+Environment.NewLine, Proc. PrivateMemorySize64, Proc. VirtualMemorySize64, Proc. WorkingSet64, Proc. PagedMemorySize64, Proc. PagedSystemMemorySize64, Proc. NONPAGEDSYSTEMMEMORYSIZE64);
9 using the stopwatch to check the program run time
If you are concerned that some code is very time consuming, you can use stopwatch to check how long this code consumes, as shown in the following code
System.Diagnostics.Stopwatch timer =NewSystem.Diagnostics.Stopwatch (); timer. Start (); Decimal Total=0; intLimit =1000000; for(inti =0; i < limit; ++i) { total= Total +(Decimal) math.sqrt (i);} Timer. Stop (); Console.WriteLine ("Sum of Sqrts: {0} ", total); Console.WriteLine ("Elapsed milliseconds: {0} ", timer. Elapsedmilliseconds); Console.WriteLine ("Elapsed time: {0} ", timer. Elapsed);
There are now specialized tools to detect the running time of the program, which can be refined to each method, such as the Dotnetperformance software.
In the above code example, you need to modify the source code directly, if it is used to test the program, it is not convenient. Please refer to the example below.
class AutoStopwatch:System.Diagnostics.Stopwatch, IDisposable { public autostopwatch () { Start (); } Public void Dispose () { Stop (); Console.WriteLine ("Elapsed: {0this. Elapsed);
With the using syntax, as shown in the following code, you can check the run time of a piece of code and print it on the console.
using (new Autostopwatch ()) { 0; int 1000000 ; for (int0; i < limit2; + +i) { = Total2 + (Decimal) math.sqrt (i);
10 using the cursor
You should modify the cursor state to busy when the program is running in the background or when the book is in addition to the operation. You can use the following tips.
classautowaitcursor:idisposable {PrivateControl _target;PrivateCursor _prevcursor =Cursors.Default; Publicautowaitcursor (Control control) {if(Control = =NULL) { Throw NewArgumentNullException ("control"); } _target=control; _prevcursor=_target. Cursor; _target. Cursor=Cursors.waitcursor;} Public voidDispose () {_target. Cursor=_prevcursor;} }
The usage is as follows, in order to anticipate that the program may throw an exception
using (new autowaitcursor (ThisthrowNew
As the code shows, even if an exception is thrown, the cursor can revert to the state between.
10 useful Code Snippets that C # programmers often use