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的更多相关文章

  1. WindowsAPI调用和OCR图片识别

    傻了吧唧的装双系统.成功的干崩了原本的系统.现在重装VS.闲的没事胡扯几句. WindowsAPI在每一台Windows系统上开放标准API供开发人员调用.功能齐全.在这里只介绍三个部分. 1.利用A ...

  2. [原创]C#应用WindowsApi实现查找(FindWindowEx)文本框(TextBox、TextEdit)。

    /// <summary> /// 获取文本框控件 /// </summary> /// <param name="hwnd">文本框所在父窗口 ...

  3. [原创]C#应用WindowsApi实现查找\枚举(FindWindow、EnumChildWindows)窗体控件,并发送消息。

    首先介绍基本WindowsApi: public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 函 ...

  4. 多媒体(3):基于WindowsAPI的视频捕捉卡操作

    目录 多媒体(1):MCI接口编程 多媒体(2):WAVE文件格式分析 多媒体(3):基于WindowsAPI的视频捕捉卡操作 多媒体(4):JPEG图像压缩编码 多媒体(3):基于WindowsAP ...

  5. Windows服务启动进程----Cjwdev.WindowsApi.dll

    windows服务下无法启动外部程序 做一个windows服务监听服务,涉及到windows服务启动外部程序的一个过程,但是调试测试发现,无法简单的用process.start()这种方法, 原因是在 ...

  6. WindowsAPI每日一练(2) 使用应用程序句柄

    WindowsAPI每日一练系列 :https://www.cnblogs.com/LexMoon/category/1246238.html WindowsAPI每日一练() WinMain Win ...

  7. WindowsAPI每日一练(1) MessageBoxA

    WindowsAPI每日一练系列 :https://www.cnblogs.com/LexMoon/category/1246238.html WindowsAPI每日一练(1) WinMain 要跟 ...

  8. 使用WindowsAPI播放PCM音频

    这一篇文章同上一篇<使用WindowsAPI获取录音音频>原理具有相似之处,不再详细介绍函数与结构体的参数 1. waveOutGetNumDevs 2. waveOutGetDevCap ...

  9. 使用WindowsAPI实现播放PCM音频的方法

    这篇文章主要介绍了使用WindowsAPI实现播放PCM音频的方法,很实用的一个功能,需要的朋友可以参考下 本文介绍了使用WindowsAPI实现播放PCM音频的方法,同前面一篇使用WindowsAP ...

  10. 使用WindowsAPI获取录音音频的方法

    这篇文章主要介绍了使用WindowsAPI获取录音音频的方法,非常实用的功能,需要的朋友可以参考下 本文实例介绍了使用winmm.h进行音频流的获取的方法,具体步骤如下: 一.首先需要包含以下引用对象 ...

随机推荐

  1. System.setProperty 与 System.getProperty

    转自:https://www.cnblogs.com/woftlcj/p/8404451.html System可以有对标准输入,标准输出,错误输出流:对外部定义的属性和环境变量的访问:加载文件和库的 ...

  2. Redis学习笔记(八) 基本命令:SortedSet操作

    原文链接:http://doc.redisfans.com/sorted_set/index.html SortedSet的数据结构类似于Set,不同的是Sorted中的每个成员都分配了一个值(Sco ...

  3. Exception异常常见属性

    废话少说,直接上代码: try { int n = Convert.ToInt32("@"); } catch(Exception ex) { Console.WriteLine( ...

  4. Spinner与适配器模式总结

    今天开始编辑我的第一篇博客. ------------------------------------------------------------------------------------- ...

  5. python pip fatal error in launcher unable to create process using

    用pip安装一个包,不知道为啥,就报了这个错误:python pip fatal error in launcher unable to create process using “”   百度了一下 ...

  6. Maven配置,使用IntelliJ IDEA和Maven创建Java Web项目

    1. 下载Maven 官方地址:http://maven.apache.org/download.cgi 解压并新建一个本地仓库文件夹 2.配置本地仓库路径   3.配置maven环境变量     4 ...

  7. 优动漫结合Photoshop怎么画草地?

    今天继续技法教学~草地的技法,PS教学~但是很简单,都是默认工具,而且是常用工具VS常用设置.你肯定会学会的! 草地教程,就到这里啦!有兴趣的可以尝试画一画哦,想要Get到更多有关优动漫的信息包括软件 ...

  8. Django中ORM之创建模型

    ORM 数据库与ORM映射关系 表名 --- 类名 字段 --- 属性 表记录 --- 类示例对象 创建表(建立模型) 模型建立如下 class Book(models.Model): title = ...

  9. 从url获取参数有中文时会出现乱码的问题

    http://192.168.1.133/v2?groupId=58&opFlag=1&result=C,B,B,B,D&Name=本人很帅 我们js获取的url中的Name其 ...

  10. python安装Redis数据库

    where pip cd 切换这个目录 pip install redis import redis r = redis.Redis(host='127.0.0.1', port=6379) user ...