C# WindowsAPI
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# WindowsAPI的更多相关文章
- WindowsAPI调用和OCR图片识别
傻了吧唧的装双系统.成功的干崩了原本的系统.现在重装VS.闲的没事胡扯几句. WindowsAPI在每一台Windows系统上开放标准API供开发人员调用.功能齐全.在这里只介绍三个部分. 1.利用A ...
- [原创]C#应用WindowsApi实现查找(FindWindowEx)文本框(TextBox、TextEdit)。
/// <summary> /// 获取文本框控件 /// </summary> /// <param name="hwnd">文本框所在父窗口 ...
- [原创]C#应用WindowsApi实现查找\枚举(FindWindow、EnumChildWindows)窗体控件,并发送消息。
首先介绍基本WindowsApi: public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 函 ...
- 多媒体(3):基于WindowsAPI的视频捕捉卡操作
目录 多媒体(1):MCI接口编程 多媒体(2):WAVE文件格式分析 多媒体(3):基于WindowsAPI的视频捕捉卡操作 多媒体(4):JPEG图像压缩编码 多媒体(3):基于WindowsAP ...
- Windows服务启动进程----Cjwdev.WindowsApi.dll
windows服务下无法启动外部程序 做一个windows服务监听服务,涉及到windows服务启动外部程序的一个过程,但是调试测试发现,无法简单的用process.start()这种方法, 原因是在 ...
- WindowsAPI每日一练(2) 使用应用程序句柄
WindowsAPI每日一练系列 :https://www.cnblogs.com/LexMoon/category/1246238.html WindowsAPI每日一练() WinMain Win ...
- WindowsAPI每日一练(1) MessageBoxA
WindowsAPI每日一练系列 :https://www.cnblogs.com/LexMoon/category/1246238.html WindowsAPI每日一练(1) WinMain 要跟 ...
- 使用WindowsAPI播放PCM音频
这一篇文章同上一篇<使用WindowsAPI获取录音音频>原理具有相似之处,不再详细介绍函数与结构体的参数 1. waveOutGetNumDevs 2. waveOutGetDevCap ...
- 使用WindowsAPI实现播放PCM音频的方法
这篇文章主要介绍了使用WindowsAPI实现播放PCM音频的方法,很实用的一个功能,需要的朋友可以参考下 本文介绍了使用WindowsAPI实现播放PCM音频的方法,同前面一篇使用WindowsAP ...
- 使用WindowsAPI获取录音音频的方法
这篇文章主要介绍了使用WindowsAPI获取录音音频的方法,非常实用的功能,需要的朋友可以参考下 本文实例介绍了使用winmm.h进行音频流的获取的方法,具体步骤如下: 一.首先需要包含以下引用对象 ...
随机推荐
- 什么是EL表达式
转自:https://blog.csdn.net/hj7jay/article/details/51302466 1. EL表达式主要作用 EL表达式说白了,就是让JSP写起来更加方便,它属于JSP技 ...
- .NET XML POST 请求
//请求体,XML参数 string xmlstring = @"<root></root>“; //请求URL string postUrl ="http ...
- IE,表头固定
<html> <head> <title>表头固定</title> <style type="text/css"& ...
- ATL and MFC String Conversion Macros
ATL 7.0介绍了一些新的转换类和宏,为现有的宏提供了重要的改进.新的字符串转换类和名称宏的形式是:C 源类型 2[C] 目标类型[EX]其中:•源类型和目标类型描述如下表.• [C]是目标类型必须 ...
- MFC+OpenGL可编程管线
[github链接] 网上的代码大都是固定管线渲染的,今天下午整理了下,把setPixelFormat.初始化glew.创建GL 4,2 context等操作封装到一个MFC类OpenGLWidget ...
- Xcode7 下导入第三方库 图文介绍
网上没有很好的图文介绍,干脆我自己写一个好了,方便新手入门. 这里以导入著名的第三方网络库AFNetWorking v3.0.4和数据库FMDB v2.6.2为例进行说明. 好,下面开始. 下载源文件 ...
- 前端精选文摘:css之BFC 神奇背后的原理(转载)
一.BFC是什么? 在解释 BFC 是什么之前,需要先介绍 Box.Formatting Context的概念. Box: CSS布局的基本单位 Box 是 CSS 布局的对象和基本单位, 直观点来说 ...
- div纵向居中的方法(转载)
方法一这个方法把一些 div 的显示方式设置为表格,因此我们可以使用表格的 vertical-align property 属性. <div id="wrapper"> ...
- DOS下格式化移动硬盘
有的时候移动硬盘出现问题,在Win下没法操作,只能到dos下格式化.以下是用Win自带的diskpart完成格式化. 1 win + r -> cmd 进入dos 2 diskpart ...
- Pyhton学习——Day39
# CSS的常用属性# 1 颜色属性# <div style="color:rgb(255,0,0)">ppppp</div># 2 字体属性# font- ...