程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# WindowsAPI,

C# WindowsAPI,

編輯:C#入門知識

C# WindowsAPI,


Windows是一個強大的操作系統,也會向開發者提供海量的系統API來幫助開發者來完成Windows系統軟件的開發工作。

整理的部分Windows API,C#可以直接調用。

1.獲取.exe應用程序的圖標

1 [DllImport("shell32.DLL", EntryPoint = "ExtractAssociatedIcon")]  
2 private static extern int ExtractAssociatedIconA(int hInst, string lpIconPath, ref int lpiIcon); //聲明函數  
3    System.IntPtr thisHandle;  
4    public System.Drawing.Icon GetIco(string filePath)//filePath是要獲取文件路徑,返回ico格式文件  
5    {  
6        int RefInt = 0;  
7        thisHandle = new IntPtr(ExtractAssociatedIconA(0, filePath, ref RefInt));  
8        return System.Drawing.Icon.FromHandle(thisHandle);  
9    }

2.獲取硬盤信息

public string GetComputorInformation()  
       {  
              
               StringBuilder mStringBuilder = new StringBuilder();  
               DriveInfo[] myAllDrivers = DriveInfo.GetDrives();  
               try  
               {  
                   foreach (DriveInfo myDrive in myAllDrivers)  
                   {  
                       if (myDrive.IsReady)  
                       {  
                           mStringBuilder.Append("磁盤驅動器盤符:");  
                           mStringBuilder.AppendLine(myDrive.Name);  
                           mStringBuilder.Append("磁盤卷標:");  
                           mStringBuilder.AppendLine(myDrive.VolumeLabel);  
                           mStringBuilder.Append("磁盤類型:");  
                           mStringBuilder.AppendLine(myDrive.DriveType.ToString());  
                           mStringBuilder.Append("磁盤格式:");  
                           mStringBuilder.AppendLine(myDrive.DriveFormat);  
                           mStringBuilder.Append("磁盤大小:");  
                           decimal resultmyDrive = Math.Round((decimal)myDrive.TotalSize / 1024 / 1024 / 1024, 2);  
                           mStringBuilder.AppendLine(resultmyDrive "GB");  
                           mStringBuilder.Append("剩余空間:");  
                           decimal resultAvailableFreeSpace = Math.Round((decimal)myDrive.AvailableFreeSpace / 1024 / 1024 / 1024, 2);  
                           mStringBuilder.AppendLine(resultAvailableFreeSpace "GB");  
                           mStringBuilder.Append("總剩余空間(含磁盤配額):");  
                           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.開機啟動程序

//獲取注冊表中的啟動位置  
        RegistryKey RKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);  
        ///<summary>/// 設置開機啟動  
        ///</summary>///<param name="path"/>public void StartRunApp(string path)  
        {  
            string strnewName = path.Substring(path.LastIndexOf("\\") 1);//要寫入注冊表的鍵值名稱  
            if (!File.Exists(path))//判斷指定的文件是否存在  
                return;  
            if (RKey == null)  
            {  
                RKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");  
            }  
            RKey.SetValue(strnewName, path);//通過修改注冊表,使程序在開機時自動運行  
        }  
        ///<summary>/// 取消開機啟動  
        ///</summary>///<param name="path"/>public void ForbitStartRun(string path)  
        {  
            string strnewName = path.Substring(path.LastIndexOf("\\") 1);//要寫入注冊表的鍵值名稱  
            RKey.DeleteValue(strnewName, false);//通過修改注冊表,取消程序在開機時自動運行  
        }

4.系統熱鍵操作

[DllImport("user32.dll")] //聲明api函數  
       public static extern bool RegisterHotKey(  
        IntPtr hwnd, // 窗口句柄  
        int id, // 熱鍵ID  
        uint fsmodifiers, // 熱鍵修改選項   
        Keys vk // 熱鍵  
       );  
       [DllImport("user32.dll")] //聲明api函數  
       public static extern bool UnregisterHotKey(  
        IntPtr hwnd, // 窗口句柄   
        int id // 熱鍵ID   
       );  
       public enum keymodifiers //組合鍵枚舉  
       {  
           none = 0,  
           alt = 1,  
           control = 2,  
           shift = 4,  
           windows = 8  
       }  
       private void processhotkey(Message m) //按下設定的鍵時調用該函數  
       {  
           IntPtr id = m.WParam; //intptr用於表示指針或句柄的平台特定類型  
           //messagebox.show(id.tostring());  
           string sid = id.ToString();  
           switch (sid)  
           {  
               case "100":  
   
                   break;  
               case "200":  
   
                   break;  
           }  
       }  
       ///<summary>/// 注冊熱鍵  
       ///</summary>public void RegisterHotkey(IntPtr handle, int hotkeyID, uint fsmodifiers, Keys mKeys)  
       {  
           RegisterHotKey(handle, hotkeyID, fsmodifiers, mKeys);  
       }  
   
       ///<summary>/// 卸載熱鍵  
       ///</summary>///<param name="handle"/>///<param name="hotkeyID"/>public void UnregisterHotkey(IntPtr handle, int hotkeyID)  
       {  
           UnregisterHotKey(handle, hotkeyID);  
       }

5.系統進程操作

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);  
   
        //定義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;  
        }  
   
        //定義內存的信息結構  
        [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;  
        }  
   
        //定義系統時間的信息結構  
        [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;  
        }  
   
        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>/// 獲取當前所有進程  
        ///</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);  
                //有些進程無法獲取啟動時間和文件名信息,所以要用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>/// 結束進程  
        ///</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.改變窗口

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

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved