Visual C # Design multifunction shutdown Program

Source: Internet
Author: User
Tags building windows contains count datetime file size modifier set time tostring
visual| Program | design


Many software have the automatic shutdown function, especially in the long time downloading, this function but lets you not wait in front of the computer, but the computer can according to you beforehand set up automatically closes. Now we use Visual C # to write a versatile shutdown program. The program has: Timing shutdown, countdown shutdown, shutdown reminder, System Information acquisition, such as four functions, can set the shutdown time accurate to the second. And let you quickly grasp the operating procedures for APIs in Visual C #.



  A. Design close Windows Forms

1. The design of the interface

Create a new standard project, add a Windows Form to the project, and include the following controls on the form, and set their properties individually:


Control Name Category Text Control Name Category Text
CheckBox1 CheckBox Automatic shutdown GroupBox1 GroupBox Current system time
CheckBox1 CheckBox Countdown Execution Action GroupBox2 GroupBox Set time
CheckBox1 CheckBox Timed Alarm Txttime Textbox
Butcancle Button Cancel Setuptime DateTimePicker
Butreopen Button Reboot Setupdate DateTimePicker
Butclose Button Shutdown Timer1 Timer 100
Butsysinto Button System Information Butrelogin Button Injection and elimination


Windows Forms Interface:






Set the caption in the form properties to "Turn off Windows" and the name is set to "Frmmain".

2. Referencing API functions in form classes

API functions are the cornerstone of building Windows applications and are 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.

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;
Using System.Text;

After importing the namespaces, we want to declare the API functions to be used in the program. Our program is mainly to  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 ("user32")]
public static extern long SetWindowPos (long hwnd, long hwndinsertafter, long X, long y, long CX, long CY, long Wflagslo NG);

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.

Declare other API functions that you want to use in your program:

[DllImport ("user32")]
public static extern long ExitWindowsEx (long uflags, long dwreserved);
[DllImport ("Shell32")]
public static extern long Shellabout (long uflags, long dwreserved);

3. Increase the variables of the form class

Long dwreserved;
const int SHUTDOWN = 1;
const int REBOOT = 2;
const int LOGOFF = 0;
Long sh;
int counter, n;

4. Ways to write form classes

Write the following code in the form's Load (event procedure:

private void Frmmain1_load (object sender, System.EventArgs e)
{
FILE://System Time Initialization component
Time.Text = System.DateTime.Today.ToShortDateString () + "" + System.DateTime.Today.ToLongTimeString ();
}

Write the following code in the OnTimer event procedure for the component Timer1:

//write the following code in the OnTimer event procedure for component Timer1:
private void Timer1_timer (object sender, System.EventArgs e)
{
file://receive the current date and time for immediate display
String currdate=system.datetime.today.toshortdatestring ();
String currtime=system.datetime.today.toshorttimestring ();
file://at any time to detect the setting of the shutdown date and time is valid
if (this. checkbox1.checked = = True)
{
if (currdate== setupdate.tostring () && currtime==setuptime.tostring ())
Colsecomputer ();
}
}
private void Colsecomputer ()
{sh = exitwindowsex (SHUTDOWN, dwreserved);}
private void Button1_Click (object sender, System.EventArgs e)
{
Form2 frm=new Form2 ();
frm. Show ();
}
private void Butreopen_click (object sender, System.EventArgs e)
{sh = exitwindowsex (REBOOT, dwreserved);}
private void Butrelogin_click (object sender, System.EventArgs e)
{sh = exitwindowsex (LOGOFF, dwreserved);}
private void Butcancle_click (object sender, System.EventArgs e)
{this. Close (); }
private void Butclose_click_1 (object sender, System.EventArgs e)
{sh = exitwindowsex (REBOOT, dwreserved);}

   two. Design a Windows Form to get system Information

1. The design of the interface

Add a Windows Form to the project, adding the following controls to the form:



2. Referencing API functions in form classes

Using System.Runtime.InteropServices;
Using System.Text;
[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);

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.

3. Define the following structures

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 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;
}

FILE://defines 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;
}

FILE://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;
}

5. Ways to write form classes

private void Button1_Click (object sender, System.EventArgs e)
{
FILE://calls the GetWindowsDirectory and GetSystemDirectory functions to obtain Windows paths and system paths, 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 ();

file://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 ();

file://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";

file://call 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";
}

   three. Concluding remarks.

This paper describes the whole process of developing a multifunction shutdown program in Visual C #, which has some practical value. 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 simply a simple program, but interested readers can further refine their functionality and make a more perfect system application.


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.