zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    Elementary Methods in Number Theory Exercise 1.2.25
    Elementary Methods in Number Theory Exercise 1.2.14
    图解欧几里德算法
    图解欧几里德算法
    Elementary Methods in Number Theory Exercise 1.2.14
    Android中的长度单位详解(dp、sp、px、in、pt、mm)
    分享下多年积累的对JAVA程序员成长之路的总结
    android异常之都是deamon惹的祸The connection to adb is down, and a severe error has occured.
    TomatoCartv1.1.8.2部署时报错
    JavaScript浏览器对象之二Document对象
  • 原文地址:https://www.cnblogs.com/BookCode/p/5324072.html
Copyright © 2011-2022 走看看