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进行音频流的获取的方法,具体步骤如下: 一.首先需要包含以下引用对象 ...
随机推荐
- intelliJ idea运行新的test功能时,报错:class not found "....." empty test suite
转自:https://blog.csdn.net/u012560212/article/details/75037578
- POJ 3660 Floyd传递闭包
题意:牛有强弱,给出一些牛的强弱的胜负关系,问可以确定几头牛的排名. 思路: Floyd传递闭包 // by SiriusRen #include <bitset> #include &l ...
- JavaScript中闭包的理解
1.什么是闭包 我个人理解闭包就是函数中嵌套函数,但是嵌套的那个函数必须是返回值,才构成闭包: <!DOCTYPE html> <html> <head> < ...
- Java中更精确的计时
我们一般的java运输计时代码是 long begintime = System.currentTimeMillis(); //运算代码 long endtinme=System.currentTim ...
- 为什么叫Unity3d为脚本语言
初接触Unity,看到大家说的都是工作主要是写脚本语言. 一直纳闷为什么说脚本语言呢,c#可不是脚本语言啊. -- -- 后来释然,说它是脚本语言是因为传统程序都是由代码构成的(像iOS.Androi ...
- JavaScript中必记英语单词及含义
reflow[ri'flo]:回流,重构(通过css改变页面的结构,比如一行元素,其中一个元素的高改变了,那么其他元素的位置也都会改变) repaint['ripent]:重绘(只改变页面的样式,比如 ...
- LayUI中select下拉框选中触发事件
代码: var form = layui.form, layer = layui.layer; // 监听 $(document).ready(function() { // select下拉框选中触 ...
- luogu P5290 [十二省联考2019]春节十二响 优先队列_启发式合并
思维难度不大,在考上上写的启发式合并写错了,只拿了 60 pts,好难过QAQ 没什么太难的,在考场上想出链的部分分之后很容易就能想到正解.没错,就是非常短的启发式合并.注意一下,写的要漂亮一点,否则 ...
- 路飞学城Python-Day32
36-进程池线程池 开多线程实现并发的效率是高的,当用户没有那么多的时候,服务器是可以承受压力的 但是一定要以某种方式来设置并发数,让服务器能够实现稳定的运行,控制服务器的线程数 设置池,往里面放池的 ...
- Vue双向绑定原理(源码解析)---getter setter
Vue双向绑定原理 大部分都知道Vue是采用的是对象的get 和set方法来实现数据的双向绑定的过程,本章将讨论他是怎么利用他实现的. vue双向绑定其实是采用的观察者模式,get和s ...