C # WindowsAPI,

Source: Internet
Author: User

C # WindowsAPI,

Windows is a powerful operating system. It also provides developers with a large number of system APIs to help developers develop Windows system software.

For some Windows APIs, C # can be called directly.

1. the icon of the .exe application is obtained.

1 [DllImport ("shell32.DLL", EntryPoint = "ExtractAssociatedIcon")] 2 private static extern int ExtractAssociatedIconA (int hInst, string lpIconPath, ref int lpiIcon); // declare function 3 System. intPtr thisHandle; 4 public System. drawing. icon GetIco (string filePath) // filePath is the file path to be obtained. The ico format file 5 {6 int RefInt = 0; 7 thisHandle = new IntPtr (ExtractAssociatedIconA (0, filePath, ref RefInt); 8 return System. drawing. icon. fromHandle (thisHandle); 9}

2. Obtain hard disk Information

Public string GetComputorInformation () {StringBuilder mStringBuilder = new StringBuilder (); DriveInfo [] myAllDrivers = DriveInfo. getDrives (); try {foreach (DriveInfo myDrive in myAllDrivers) {if (myDrive. isReady) {mStringBuilder. append ("disk drive letter:"); mStringBuilder. appendLine (myDrive. name); mStringBuilder. append ("disk volume label:"); mStringBuilder. appendLine (myDrive. volumeLabel); mStringBuilder. append ("disk type:"); mStringBuilder. appendLine (myDrive. driveType. toString (); mStringBuilder. append ("disk format:"); mStringBuilder. appendLine (myDrive. driveFormat); mStringBuilder. append ("disk size:"); decimal resultmyDrive = Math. round (decimal) myDrive. totalSize/1024/1024/1024, 2); mStringBuilder. appendLine (resultmyDrive "GB"); mStringBuilder. append ("available space:"); decimal resultAvailableFreeSpace = Math. round (decimal) myDrive. availableFreeSpace/1024/1024/1024, 2); mStringBuilder. appendLine (resultAvailableFreeSpace "GB"); mStringBuilder. append ("total available space (including Disk Quota):"); decimal resultTotalFreeSpace = Math. round (decimal) myDrive. totalFreeSpace/1024/1024/1024, 2); mStringBuilder. appendLine (resultTotalFreeSpace "GB"); mStringBuilder. appendLine ("-----------------------------------") ;}} catch (Exception ex) {throw ex;} return mStringBuilder. toString ();}

3. Start the program

// Obtain the Registry Startup location RegistryKey RKey = Registry. localMachine. openSubKey ("SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ Run", true ); /// <summary> /// set boot start /// </summary> /// <param name = "path"/> public void StartRunApp (string path) {string strnewName = path. substring (path. lastIndexOf ("\") 1); // if (! File. exists (path) // determines whether the specified file has a return; if (RKey = null) {RKey = Registry. localMachine. createSubKey ("SOFTWARE \ Microsoft \ Windows \ CurrentVersion \ Run");} RKey. setValue (strnewName, path); // modify the registry, enable the program to run automatically at startup} // <summary> // cancel startup /// </summary> /// <param name = "path"/> public void ForbitStartRun (string path) {string strnewName = path. substring (path. lastIndexOf ("\") 1); // name of the key to be written to the Registry RKey. deleteValue (strnewName, false); // by modifying the registry, cancel the program to run automatically at startup}

4. System hotkey operation

[DllImport ("user32.dll")] // declare the api function public static extern bool RegisterHotKey (IntPtr hwnd, // window handle int id, // hotkey ID uint fsmodifiers, // hotkey modify option Keys vk // hotkey); [DllImport ("user32.dll")] // declare the api function public static extern bool UnregisterHotKey (IntPtr hwnd, // window handle int id // hotkey ID); public enum keymodifiers // key combination enumeration {none = 0, alt = 1, control = 2, shift = 4, windows = 8} private void processhotkey (Message m) // call this function {IntPtr id = m when you press the set key. WParam; // intptr indicates the platform-specific type of pointer or handle. // messagebox. show (id. tostring (); string sid = id. toString (); switch (sid) {case "100": break; case "200": break ;}} /// <summary> /// register the hotkey /// </summary> public void RegisterHotkey (IntPtr handle, int hotkeyID, uint fsmodifiers, Keys mKeys) {RegisterHotKey (handle, hotkeyID, fsmodifiers, mKeys );} /// <summary> /// uninstall the hotkey /// </summary> /// <param name = "handle"/> /// <param name = "hotkeyID" /> public void UnregisterHotkey (IntPtr handle, int hotkeyID) {UnregisterHotKey (handle, hotkeyID );}

5. system process operations

Public class GetProcess {bool isSuccess = false; [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 ); // define the CPU information structure [StructLayout (LayoutKind. sequential)] public struct CPU_INFO {public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint role; public uint dwProcessorType; public uint role; public uint dwProcessorLevel; public uint dwProcessorRevision;} // defines the memory information structure [StructLayout (LayoutKind. sequential)] public struct MEMORY_INFO {public uint dwLength; public uint dwMemoryLoad; public uint dwTotalPhys; public uint values; public uint dwTotalVirtual; public uint dwAvailVirtual ;} // define the system time information structure [StructLayout (LayoutKind. sequential)] public struct SYSTEMTIME_INFO {public ushort wYear; public ushort wMonth; public ushort week; public ushort wDay; public ushort wHour; public ushort wMinute; public ushort wSecond; public ushort second ;} public string GetSystemInformation () {MEMORY_INFO MemInfo = new MEMORY_INFO (); GlobalMemoryStatus (ref MemInfo); return MemInfo. dwMemoryLoad. toString ();} public string GetSystemCup () {CPU_INFO CpuInfo = new CPU_INFO (); GetSystemInfo (ref CpuInfo); return CpuInfo. dwProcessorType. toString () ;}/// <summary> /// obtain all processes currently /// </summary> /// <returns> </returns> public DataTable GetAllProcess () {DataTable mDataTable = new DataTable (); mDataTable. rows. clear (); mDataTable. columns. add ("ProcessID"); mDataTable. columns. add ("ProcessName"); mDataTable. columns. add ("Memory"); mDataTable. columns. add ("StartTime"); mDataTable. columns. add ("FileName"); mDataTable. columns. add ("ThreadNumber"); Process [] myProcess = Process. getProcesses (); foreach (Process p in myProcess) {DataRow mDataRow = mDataTable. newRow (); mDataRow [0] = p. id; mDataRow [1] = p. processName; mDataRow [2] = string. format ("{0 :##,## 0.00} KB", p. privateMemorySize64/1024); // some processes cannot obtain the start time and file name information, so try/catch; try {mDataRow [3] = string. format ("{0}", p. startTime); mDataRow [4] = p. mainModule. fileName; mDataRow [5] = p. threads. count;} catch {mDataRow [3] = ""; mDataRow [4] = "";} mDataTable. rows. add (mDataRow);} return mDataTable ;} /// <summary> /// end the process /// </summary> /// <param name = "processName"/>/// <returns> </returns> public bool KillProcess (string processName) {try {System. diagnostics. process [] process = System. diagnostics. process. getProcessesByName (processName); foreach (System. diagnostics. process p in process) {p. kill () ;}} catch {isSuccess = false;} return isSuccess ;}}

6. Change the window

public const int SE_SHUTDOWN_PRIVILEGE = 0x13;            [DllImport("user32.dll")]         public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);            [DllImport("user32.dll")]         public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);            [DllImport("user32.dll")]         public static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx,             int cy, uint uFlags);

 

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.