Using API functions to obtain system information in Visual C #

Source: Internet
Author: User
Tags define definition building windows count file size modifier tostring
The Visual| function API function is the cornerstone of building Windows applications and is a necessary tool for Windows programming. Each of the Windows Application development tools provides a way to indirectly or directly invoke Windows API functions, or interfaces that invoke Windows API functions, which means the ability to invoke dynamic connection libraries. Visual C #, like other development tools, can also invoke the API functions of a dynamic-link library. In this article, the author introduces the API of how to invoke various return values in Visual C #, which is a program that obtains system information through API function call.

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

First, before invoking the API, you must first import the System.Runtime.InteropServices namespace. This namespace contains some of the necessary collections of calls to the API in Visual C #, as follows:

Using System.Runtime.InteropServices;

After importing the namespaces, we want to declare the API functions to be used in the program. Our program is mainly to obtain information about the system, so the use of API functions are returned to the system information. First, give the method of declaring the API in Visual C #:

[DllImport ("kernel32")]
public static extern void GetWindowsDirectory (StringBuilder windir,int count);

Where the "DllImport" property is used to call a method from within the controllable code that specifies the location of the DLL that contains the external method of the call; "KERNEL32" Sets the class library name; "Public" indicates that the access type of the function is common; "Static" modifier declares a static element that belongs to the type itself rather than the specified object; "extern" means that the method will be executed outside the project, and the method imported using DllImport must use the "extern" modifier The last GetWindowsDirectory function contains two arguments, one is StringBuilder type and the other is of type int, and the method returns content that exists in the parameters of the StringBuilder type. At the same time, because we use the StringBuilder class here, at the beginning of the program, we have to add the System.Text namespace, the same method as above.

Several other API functions are declared 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 function of the above API is to obtain the system path, obtain the CPU related information, obtain the related information of the memory, obtain the system time and so on.
After declaring all the API functions, we found that the following three functions were used in Cpu_info, Memory_info, Systemtime_info, and so on, and these structures are not. NET inside, where do they come from? In fact, we use the above API calls are required to the above structure, we will be the function call to obtain the information stored in the above structure, and finally returned to the program output. These structures are more complex, but if developers are proficient, the entire API world will be in the hands of developers. The following is the statement of the above structure:

Define the following structures
Define the information 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;
}

Defining the information structure of memory
[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;
}

Information structure to define system time
[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;
}

The body part of the structure definition is not much different from C + +, and the definition of the member within each structure can refer to the SDK documentation in the online Help. At the same time, we also find that there is a descriptive text enclosed in brackets in each structure definition. These instructions are for the layout of the members of the structure, and there are three options, respectively, as follows:

Layoutkind.automatic: Allows the running state to reorder type members in order to improve efficiency.

Note: Never use this option to invoke a dynamically linked library function that is not governed.

LAYOUTKIND.EXPLICIT: Sorting type members by FieldOffset property for each field

LayoutKind.Sequential: Sorts the members of a type that appear in the domain of the jurisdiction type definition where they are not in the governed memory.

In the above program, for the sake of convenience we have used a third way.

After all the API functions and associated structures are declared, we use these APIs to implement our program functions-to get information about the system.

Interface can be arranged as follows, but interested readers can naturally play their own imagination, the interface layout to do a better job.








After the simple interface is arranged, we add a button (Get Info button) message processing function as follows:

private void Getinfo_click (object sender, System.EventArgs e)
{
Call the GetWindowsDirectory and GetSystemDirectory functions to get the Windows path and system path, respectively
const int nchars = 128;
StringBuilder Buff = new StringBuilder (nchars);
GetWindowsDirectory (Buff,nchars);
Windowsdirectory.text = "Windows path:" +buff.tostring ();
GetSystemDirectory (Buff,nchars);
Systemdirectory.text = "System path:" +buff.tostring ();

Call the GetSystemInfo function to get information about the CPU
Cpu_info CpuInfo;
CpuInfo = new Cpu_info ();
GetSystemInfo (ref CpuInfo);
Numberofprocessors.text = "The computer has" +cpuinfo.dwnumberofprocessors.tostring () + "CPU";
Processortype.text = "Type of CPU is" +cpuinfo.dwprocessortype.tostring ();
Processorlevel.text = "CPU level is" +cpuinfo.dwprocessorlevel.tostring ();
Oemid.text = "CPU OEM ID is" +cpuinfo.dwoemid.tostring ();
Pagesize.text = "Page size in CPU is" +cpuinfo.dwpagesize.tostring ();

Call the GlobalMemoryStatus function to get information about the memory
Memory_info Meminfo;
Meminfo = new Memory_info ();
GlobalMemoryStatus (ref meminfo);
Memoryload.text = MemInfo.dwMemoryLoad.ToString () + "% of memory is in use";
Totalphys.text = "Physical Memory Total" +meminfo.dwtotalphys.tostring () + "byte";
Availphys.text = "Available physical inner Existence" +meminfo.dwavailphys.tostring () + "byte";
Totalpagefile.text = "The total size of the swap file is" +meminfo.dwtotalpagefile.tostring () + "byte";
Availpagefile.text = "The file size is" +meminfo.dwavailpagefile.tostring () + "bytes";
Totalvirtual.text = "Total virtual inner existence" +meminfo.dwtotalvirtual.tostring () + "byte";
Availvirtual.text = "Not in virtual existence" +meminfo.dwavailvirtual.tostring () + "byte";

Call the GetSystemTime function to 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 () + "dot" +stinfo.wminute.tostring () + "Min" +stinfo.wsecond.tostring () + "seconds";
}

In the above message processing function, we use the various API functions declared at the beginning of the program to obtain the relevant information of the system, and finally display the result in the text label on the interface. The name of each text label can be seen in the source code accompanying the text, this is a tentative.
Finally, run the program as follows:


   Conclusion:

Through the study of this article, I believe that a developer with a little API base can immediately analogy and quickly grasp the operation of the API in Visual C #. The example given above is only a very simple example program, but interested readers can further refine their functions and make a more perfect system Information detection program.



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.