C# Windows API
API:应用程序接口(API:Application Program Interface)
应用程序接口(API:application programming interface)是一组定义、程序及协议的集合,通过 API 接口实现计算机软件之间的相互通信。API 的一个主要功能是提供通用功能集。程序员通过使用 API 函数开发应用程序,从而可以避免编写无用程序,以减轻编程任务。
API 同时也是一种中间件,为各种不同平台提供数据共享。根据单个或分布式平台上不同软件应用程序间的数据共享性能,可以将 API 分为四种类型:
远程过程调用(RPC):通过作用在共享数据缓存器上的过程(或任务)实现程序间的通信。
标准查询语言(SQL):是标准的访问数据的查询语言,通过通用数据库实现应用程序间的数据共享。
文件传输:文件传输通过发送格式化文件实现应用程序间数据共享。
信息交付:指松耦合或紧耦合应用程序间的小型格式化信息,通过程序间的直接通信实现数据共享。
当前应用于 API 的标准包括 ANSI 标准 SQL API。另外还有一些应用于其它类型的标准尚在制定之中。API 可以应用于所有计算机平台和操作系统。这些 API 以不同的格式连接数据(如共享数据缓存器、数据库结构、文件框架)。每种数据格式要求以不同的数据命令和参数实现正确的数据通信,但同时也会产生不同类型的错误。因此,除了具备执行数据共享任务所需的知识以外,这些类型的 API 还必须解决很多网络参数问题和可能的差错条件,即每个应用程序都必须清楚自身是否有强大的性能支持程序间通信。相反由于这种 API 只处理一种信息格式,所以该情形下的信息交付 API 只提供较小的命令、网络参数以及差错条件子集。正因为如此,交付 API 方式大大降低了系统复杂性,所以当应用程序需要通过多个平台实现数据共享时,采用信息交付 API 类型是比较理想的选择。
API 与图形用户接口(GUI)或命令接口有着鲜明的差别:API 接口属于一种操作系统或程序接口,而后两者都属于直接用户接口。
有时公司会将 API 作为其公共开放系统。也就是说,公司制定自己的系统接口标准,当需要执行系统整合、自定义和程序应用等操作时,公司所有成员都可以通过该接口标准调用源代码,该接口标准被称之为开放式 API。
Windows是一个强大的操作系统,也会向开发者提供海量的系统API来帮助开发者来完成Windows系统软件的开发工作。在此,向大家分享一下自己以前用到过的,整理的部分Windows API,C#可以直接调用。
1.获取.exe应用程序的图标
[DllImport("shell32.DLL", EntryPoint = "ExtractAssociatedIcon")]
private static extern int ExtractAssociatedIconA(int hInst, string lpIconPath, ref int lpiIcon); //声明函数
System.IntPtr thisHandle;
public System.Drawing.Icon GetIco(string filePath)//filePath是要获取文件路径,返回ico格式文件
{
int RefInt = ;
thisHandle = new IntPtr(ExtractAssociatedIconA(, filePath, ref RefInt));
return System.Drawing.Icon.FromHandle(thisHandle);
}
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 / / / , );
mStringBuilder.AppendLine(resultmyDrive "GB");
mStringBuilder.Append("剩余空间:");
decimal resultAvailableFreeSpace = Math.Round((decimal)myDrive.AvailableFreeSpace / / / , );
mStringBuilder.AppendLine(resultAvailableFreeSpace "GB");
mStringBuilder.Append("总剩余空间(含磁盘配额):");
decimal resultTotalFreeSpace = Math.Round((decimal)myDrive.TotalFreeSpace / / / , );
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("\\") );//要写入注册表的键值名称
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("\\") );//要写入注册表的键值名称
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 = ,
alt = ,
control = ,
shift = ,
windows =
}
private void processhotkey(Message m) //按下设定的键时调用该函数
{
IntPtr id = m.WParam; //intptr用于表示指针或句柄的平台特定类型
//messagebox.show(id.tostring());
string sid = id.ToString();
switch (sid)
{
case "": break;
case "": 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[] = p.Id;
mDataRow[] = p.ProcessName;
mDataRow[] = string.Format("{0:###,##0.00}KB", p.PrivateMemorySize64 / );
//有些进程无法获取启动时间和文件名信息,所以要用try/catch;
try
{
mDataRow[] = string.Format("{0}", p.StartTime);
mDataRow[] = p.MainModule.FileName;
mDataRow[] = p.Threads.Count; }
catch
{
mDataRow[] = "";
mDataRow[] = ""; }
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);
C# Windows API的更多相关文章
- Windows API 函数列表 附帮助手册
所有Windows API函数列表,为了方便查询,也为了大家查找,所以整理一下贡献出来了. 帮助手册:700多个Windows API的函数手册 免费下载 API之网络函数 API之消息函数 API之 ...
- Windows API Hooking in Python
catalogue . 相关基础知识 . Deviare API Hook Overview . 使用ctypes调用Windows API . pydbg . winappdbg . dll inj ...
- 初识【Windows API】--文本去重
最近学习操作系统中,老师布置了一个作业,运用系统调用函数删除文件夹下两个重复文本类文件,Linux玩不动,于是就只能在Windows下进行了. 看了一下介绍Windows API的博客: 点击打开 基 ...
- C#调用windows API的一些方法
使用C#调用windows API(从其它地方总结来的,以备查询) C#调用windows API也可以叫做C#如何直接调用非托管代码,通常有2种方法: 1. 直接调用从 DLL 导出的函数. 2. ...
- Qt中使用Windows API
在Windows平台上进行开发,不可避免与Windows API打交道,Qt中使用的时候要添加对应API的头文件和链接lib文件,另外使用的Windows API的代码部分要使用#ifdef Q_O ...
- 在VBA中使用Windows API
VBA是一种强大的编程语言,可用于自定义Microsoft Office解决方案.通过使用VBA处理一个或多个Office应用程序对象模型,可以容易地修改Office应用程序的功能或者能够使两个或多个 ...
- FormatMessage与GetLastError配合使用,排查windows api调用过程中的错误
前一段时间在学习windows api调用过程中,遇到过一些调用错误或者程序没能显示预期的结果,或者直接出现vc运行时错误. 这对新手来说是司空见惯的事,因为不太熟悉难免会出错,出错的信息如果能显示很 ...
- C#调用Windows API函数截图
界面如下: 下面放了一个PictureBox 首先是声明函数: //这里是调用 Windows API函数来进行截图 //首先导入库文件 [System.Runtime.InteropServices ...
- 【转】用C#调用Windows API向指定窗口发送
一.调用Windows API. C#下调用Windows API方法如下: 1.引入命名空间:using System.Runtime.InteropServices; 2.引用需要使用的方法,格式 ...
随机推荐
- 创建APPID&&部署服务端教程
创建APPID&&部署服务端 一.创建APPID 1.打开https://console.developers.google.com ,左击顶部Project,然后左击创建项目 2.输 ...
- prometheus监控系统
关于Prometheus Prometheus是一套开源的监控系统,它将所有信息都存储为时间序列数据:因此实现一种Profiling监控方式,实时分析系统运行的状态.执行时间.调用次数等,以找到系统的 ...
- 为什么很多SaaS企业级产品都熬不过第一年
因工作缘由,笔者与周边数位SaaS企业级应用的创始人.运营负责人有过深入接触,发现一个有趣的现象:刚起步时,蓝图远志.规划清晰,但是一路下来,却异常艰难,有些甚至熬不过第一年,就关门歇业. 2015年 ...
- JS案例之2——cycle元素轮播
元素轮播效果是页面中经常会使用的一种效果.这个例子实现了通过元素的隐藏和显示来表现轮播效果.效果比较简单. 效果图如下: 源代码如下: <!DOCTYPE html> <html&g ...
- 【AutoMapper官方文档】DTO与Domin Model相互转换(中)
写在前面 AutoMapper目录: [AutoMapper官方文档]DTO与Domin Model相互转换(上) [AutoMapper官方文档]DTO与Domin Model相互转换(中) [Au ...
- 【UWP开源】图片编辑器,带贴图、滤镜、涂鸦等功能
目录 说明 功能 实现原理 使用方法 效果截图 说明 最近空余时间研究了一下Win2D,它能为我们在UWP中提供一种类似GDI那样的绘图方法.就像传统Winform.MFC中那样重写OnPaint相关 ...
- X Window 的奥秘
大名鼎鼎的 X Window 大家肯定不陌生.都知道它是 Unix/Linux 下面的窗口系统,也都知道它基于 Server/Clinet 架构.在网上随便搜一搜,也可以找到不少 X Window 的 ...
- 用Excel做出比肩任务管理软件的操作技巧
用Excel做出比肩任务管理软件的操作技巧 在项目管理中,网上有各种各样的工具可以选择,到底用哪个,曾一度困扰着我.我是一个有轻度强迫症的人,总是喜欢试用各种各样的系统,以比较他们之间的不同,试图选择 ...
- 页面中调用系统常用的对话框需要用到的classid
■打开■ <input name=Button onClick=document.all.WebBrowser.ExecWB(1,1) type=button value=打开> < ...
- Atitti 载入类的几种方法 Class.forName ClassLoader.loadClass 直接new
Atitti 载入类的几种方法 Class.forName ClassLoader.loadClass 直接new 1.1. 载入类的几种方法 Class.forName ClassLo ...