Use the API function to get system information in Visual C #

xiaoxiao2021-04-02  251

The API function is the cornerstone of the Windows application, which is a must-have tool for Windows programming. Each Windows application development tool provides indirect or directly calling a method of calling the Windows API function, or calling the interface of the Windows API function, that is, the ability to call the dynamic connection library. Visual C # and other development tools can also call the dynamic link library API function. In this article, the author describes how to invoke a variety of return values ​​in Visual C #, which is a program that captures the system information through the API function.

The basic process of calling the API in Visual C #:

First, before calling the API, you must first import the namespace of System.Runtime.InteropServices. The namespace contain some of the necessary collection of the API in Visual C #, the specific methods are as follows:

Using system.Runtime.InteropServices;

After importing the namespace, we must declare the API function to be used in the program. Our program is mainly information about the system, so the API function used is returned to system information. First give a method of declaring the API in Visual C #:

[DLLIMPORT ("kernel32")] public static extern void getWindowsDirectory (StringBuilder WINDIR, INT COUN);

Where "DLLIMPORT" attribute is used to call a method from the uncontrollable code, it specifies the location of the DLL, which contains the external method called; "kernel32" sets the class library name; "public" specifies the function of the function The type is public; "Static" modifier declares a static element, which is the type itself instead of the specified object; "extern" indicates that the method will execute outside, while using the DLLIMPORT import method must use "extern" The modifier; the final GetWindowsDirectory function contains two parameters, one for the StringBuilder type, the other is int type, the content returned by this method exists in the parameter of the StringBuilder type. At the same time, because we use the StringBuilder class here, we have to add the namespace of the system.text at the beginning of the program, and the method is the same.

The declarations of several other API functions are as follows:

[DllImport ( "kernel32")] public static extern void GetSystemDirectory (StringBuilder SysDir, int count); [DllImport ( "kernel32")] public static extern void GetSystemInfo (ref CPU_INFO cpuinfo); [DllImport ( "kernel32")] public static Extern Void GlobalMemoryStatus (Ref Memory_Info Meminfo); [DLLIMPORT ("Kernel32")] Public Static Extern Void GetSystemTime (Ref SystemTime_INFO STINFO);

The roles of the above APIs are acquisition system paths, obtain CPU-related information, and obtain information about memory, obtain system time, and the like.

After declaring all the API functions, we found that the three functions were used to use CPU_INFO, MEMORY_INFO, SYSTEMTIME_INFO, etc., which are not .NET inside, where did they come from? In fact, we need to use the above structure when used in the above API call, and we store the information obtained by the function call in the above structure, and finally returns to the program output. These structures are more complicated, but if the developer can be skilled, the entire API world will be in the mastery of the developer. The following statement is the above-described structure: following structure definition information // // define the structure of the CPU [StructLayout (LayoutKind.Sequential)] public struct CPU_INFO {public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision;} // define memory information structure [StructLayout (LayoutKind.Sequential)] public struct MEMORY_INFO {public uint dwLength; public uint dwMemoryLoad ; public uint dwTotalPhys; public uint dwAvailPhys; public uint dwTotalPageFile; public uint dwAvailPageFile; public uint dwTotalVirtual; public uint dwAvailVirtual;} // define the system configuration information of time [StructLayout (LayoutKind.Sequential)] public struct SYSTEMTIME_INFO {public ushort wYear; Public Ushort WMONTH; Public Ushort WDAY; Public Ushort WHOUTE; Public Ushort WSecond; Public Ushort WmilliseConds;

There are not many differences in the main body portion and C defined by the structural body, and the definition of the internal member of each structure can be referred to the SDK document in the online help. At the same time, we have also found that there is an illustrative text that has been enclosed in the middle brackets in each structural definition. These descriptions are all layouts of structural members, with three options, respectively, as follows:

LayoutKind.automatic: To improve efficiency allows the run state to reorder type members.

Note: Never use this option to call unlicensed dynamic link library functions.

LayoutKind.exPlicit: Sort by Fieldoffset property to each domain

LayoutKind.sequential: Sorting type members that appear in unlicensed memory in the jurisdiction.

In the above program, we used the third way for convenience.

All API functions and related structural declarations, we use these APIs to implement our program function - get information about the system.

The interface can be arranged as follows, but interested readers can naturally play their own imagination and make the interface layout better. After the simple interface is arranged, we add a button ("Get Information" button) The message processing function is as follows:

private void GetInfo_Click (object sender, System.EventArgs e) {// call GetSystemDirectory GetWindowsDirectory and functions are made path and Windows system path const int nChars = 128; StringBuilder Buff = new StringBuilder (nChars); GetWindowsDirectory (Buff, nChars); WindowsDirectory .Text = "Windows path:" buff.toT7tring (); getSystemDirectory; systemdirectory.text = "system path:" buff.totring (); // Call the getSystemInfo function Get the CPU_info cpuinfo ; cpuInfo = new CPU_INFO (); GetSystemInfo (ref cpuInfo); NumberOfProcessors.Text = "this computer has" CpuInfo.dwNumberOfProcessors.ToString () "a CPU"; ProcessorType.Text = "CPU type is" cpuInfo .dwprocessortype.tostring (); processorlevel.text = "CPU level is" cpuinfo.dwprocessorlevel.tostring (); OEMID.TEXT = "OEM ID of CPU" cpuinfo.dwoemid.tostring (); pagesize.text = " page size of the CPU is " CpuInfo.dwPageSize.ToString (); // call the function to get GlobalMemoryStatus memory of relevant information MEMORY_INFO MemInfo; MemInfo = new MEMORY_INFO (); GlobalMemoryStatus (ref MemInfo); MemoryLoad.Text = MemInfo.dwMemoryLoad. Tostring () "% of the memory is being used"; Totalphys.text = "Physical memory shared" MEMINFO.DWTOAL Phys.tostring () "Byte"; AvailPhys.Text = "The physical memory available" MEMINFO.DWAVAILPHYS.TOSTRING () "byte"; TotalpageFile.Text = "Switching file total size Meminfo .dwtotalpagefile.tostring () "byte"; availpagefile.text = "Mounts to exchange file size MEMINFO.DWAVAILPAGE.TOSTRINFO.DWAVAILPAGE.TOSTRING () " Byte "; TotalVirtual.Text =" Total virtual memory " MEMINFO .dwtotalvirtual.tostring () "bytes"; availvirtual.text = "There is no virtual memory" MEMINFO.DWAVAILVIRTUAL.TOSTOSTRING () "byte";

// call the function to get the system time GetSystemTime information SYSTEMTIME_INFO StInfo; StInfo = new SYSTEMTIME_INFO (); GetSystemTime (ref StInfo); Date.Text = StInfo.wYear.ToString () "of" StInfo.wMonth.ToString () " " Stinfo.wday.tostring () " day "; time.text = (stinfo.whour 8) .tostring () " point " stinfo.wminute.to.WSecond .Tostring () "second";} In the above message processing function, we used the various API functions that were declared at the beginning of the program to obtain the system's related information, and eventually display the results in the interface label on the interface. Named ways of each text tag can be found in the subsequent source code, which is temporarily.

Finally, the operator is as follows:

Conclusion: Through the study of this article, I believe that a slightly API usage based developers can touch the category bypass, soaster Master the operation of the API in Visual C #. The example given above is just a very simple sample program, but interested readers can further improve their functions and make a more perfect system information detection program.

Attached: vs.net2005 source code

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; using System.IO;

namespace SystemInfo {public partial class Form1: Form {public Form1 () {InitializeComponent ();} [DllImport ( "kernel32")] public static extern void GetWindowsDirectory (StringBuilder WinDir, int count);

[DLLIMPORT ("kernel32")] public static extern void getSystemDirectory (StringBuilder sysdir, int count);

[DLLIMPORT ("kernel32")] public static extern void getSystemInfo (Ref CPU_INFO CPUInfo);

[DLLIMPORT ("kernel32")] public static extern void globalMemoryStatus (Ref memory_info meminfo);

[DLLIMPORT ("kernel32")] public static extern void getSystemTime (Ref systemtime_info stinfo);

// // definition structure defines the structure of CPU [StructLayout (LayoutKind.Sequential)] public struct CPU_INFO {public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision;} // define memory information structure [StructLayout (LayoutKind.Sequential)] public struct MEMORY_INFO {public uint dwLength; public uint dwMemoryLoad; public uint dwTotalPhys; public uint dwAvailPhys; public uint dwTotalPageFile Public uint dwavailpagefile; public uint dwtotalvirtual; public uint dwavailvirtual;

// the system time information to be defined [StructLayout (LayoutKind.Sequential)] public struct SYSTEMTIME_INFO {public ushort wYear; public ushort wMonth; public ushort wDayOfWeek; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort Wmilliseconds;

private void timer1_Tick (object sender, EventArgs e) {// call GetSystemDirectory GetWindowsDirectory and functions are made path and Windows system path const int nChars = 128; StringBuilder Buff = new StringBuilder (nChars); GetWindowsDirectory (Buff, nChars); WindowsDirectory.Text = "Windows Path:" Buff.Tostring (); getSystemDirectory; systemdirectory.text = "System path:" buff.totring (); // Call the getSystemInfo function to get the CPU related information CPU_INFO CPUInfo; CPUInfo = new CPU_INFO (); GetSystemInfo (ref cpuInfo); NumberOfProcessors.Text = "this computer has" CpuInfo.dwNumberOfProcessors.ToString () "a CPU"; ProcessorType.Text = "CPU type is" CpuInfo.dwProcessorType .Tostring (); processorlevel.text = "CPU level is" cpuinfo.dwprocessorlevel.tostring (); OEMID.TEXT = "OEM ID of the CPU" cpuinfo.dwoemid.tostring (); pagesize.text = "CPU The page size is " cpuinfo.dwpagesize.tostring ();

// call the function to get GlobalMemoryStatus memory of relevant information MEMORY_INFO MemInfo; MemInfo = new MEMORY_INFO (); GlobalMemoryStatus (ref MemInfo); MemoryLoad.Text = MemInfo.dwMemoryLoad.ToString () "% memory in use"; TotalPhys.Text = "Physical memory shared" meminfo.dwtotalphys.tostring () "byte"; availphys.text = "available physical memory has" MEMINFO.DWAVAILPHYS.TOSTRING () "byte"; TotalPageFile.Text = " The total size of the exchange file is " MEMINFO.DWTOTALPAGE.TOSTOSTRINFO.TOTALPAGEFILE.TOSTRINFO.TOTALPAGEFILE.TOSTRINFO.TOTALPAGEFILE.TOSTRINFO.TOTALPAGEFILE.TOString () " byte "; availpagefile.text =" Mounts Sign " MEMINFO.DWAVAILPAGE.TOSTRING () " byte "; TotalVirtual.Text = "Total virtual memory" meminfo.dwtotalvirtual.tostring () "byte"; availvirtual.text = "There is no virtual memory" MEMINFO.DWAVALVIRTUAL.TOSTRING () "byte"; // Call GetSystemTime function Get system time information systemTime_info stinfo; stinfo = new systemtime_info (); getSystemTime (ref stinfo); Date.Text = stinfo.wyear.tostring () "Year" stinfo.wmonth.tostring () "Month" stinfo.wday.tostring () "day"; time.text = (stinfo.whour 8) .tostring () "point" stinfo.wminute.toTString () "points" stinfo. WSecond.toString () "second" stinfo.wmilliseconds.toString () "millisecond";

}

}

I have a bug in the process of testing, 16 o'clock, if it is changed to 4 points, running system time has an error, showing 28 points! I don't know! !

转载请注明原文地址:https://www.9cbs.com/read-131371.html

New Post(0)