C# 实现系统信息监控与获取全解析

在 C# 开发的众多应用场景中,获取系统信息以及监控用户操作有着广泛的用途。比如在系统性能优化工具中,需要实时读取 CPU、GPU 资源信息;在一些特殊的输入记录程序里,可能会涉及到键盘监控;而在图形界面开发中,获取屏幕大小是基础操作。本文将详细介绍如何使用 C# 来实现这些功能,助力大家在开发中更好地与系统底层进行交互。

一、C# 监控键盘

1. 原理与实现思路

在 Windows 系统下,可以通过 Windows API 来实现键盘监控。需要使用SetWindowsHookEx函数来设置一个钩子,当键盘事件发生时,系统会调用我们定义的回调函数来处理这些事件。

2. 代码实现

首先,需要引入System.Runtime.InteropServices命名空间,以便调用 Windows API。

cs 复制代码
using System;

using System.Runtime.InteropServices;

class KeyboardMonitor

{

// 定义委托类型

private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

// 定义钩子句柄

private static IntPtr hHook = IntPtr.Zero;

// 导入SetWindowsHookEx函数

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]

private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, uint dwThreadId);

// 导入UnhookWindowsHookEx函数

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]

[return: MarshalAs(MarshalType.Bool)]

private static extern bool UnhookWindowsHookEx(IntPtr hhk);

// 导入CallNextHookEx函数

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]

private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

// 导入GetModuleHandle函数

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]

private static extern IntPtr GetModuleHandle(string lpModuleName);

// 定义钩子类型

private const int WH_KEYBOARD_LL = 13;

// 定义键盘消息常量

private const int WM_KEYDOWN = 0x0100;

private const int WM_KEYUP = 0x0101;

// 定义回调函数

private static IntPtr KeyboardHookProc(int nCode, IntPtr wParam, IntPtr lParam)

{

if (nCode >= 0)

{

if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_KEYUP)

{

int vkCode = Marshal.ReadInt32(lParam);

Console.WriteLine($"键盘事件: {(wParam == (IntPtr)WM_KEYDOWN? "按下" : "松开")},键码: {vkCode}");

}

}

return CallNextHookEx(hHook, nCode, wParam, lParam);

}

// 安装钩子

public static void StartMonitoring()

{

using (System.Diagnostics.Process curProcess = System.Diagnostics.Process.GetCurrentProcess())

using (System.Diagnostics.ProcessModule curModule = curProcess.MainModule)

{

hHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProc, GetModuleHandle(curModule.ModuleName), 0);

if (hHook == IntPtr.Zero)

{

Console.WriteLine("设置钩子失败。");

}

}

}

// 卸载钩子

public static void StopMonitoring()

{

if (hHook!= IntPtr.Zero)

{

UnhookWindowsHookEx(hHook);

hHook = IntPtr.Zero;

}

}

}

在Main方法中可以调用KeyboardMonitor.StartMonitoring()来开始监控键盘,调用KeyboardMonitor.StopMonitoring()停止监控。

二、读取 CPU、GPU 资源信息

1. 使用 PerformanceCounter 读取 CPU 信息

PerformanceCounter类是.NET 框架提供的用于读取系统性能计数器的工具。通过它可以方便地获取 CPU 使用率等信息。

cs 复制代码
using System;

using System.Diagnostics;

class CpuMonitor

{

private PerformanceCounter cpuCounter;

public CpuMonitor()

{

cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");

}

public float GetCpuUsage()

{

return cpuCounter.NextValue();

}

}

在Main方法中使用如下:

cs 复制代码
CpuMonitor cpuMonitor = new CpuMonitor();

while (true)

{

float cpuUsage = cpuMonitor.GetCpuUsage();

Console.WriteLine($"当前CPU使用率: {cpuUsage}%");

System.Threading.Thread.Sleep(1000);

}

2. 使用第三方库读取 GPU 信息

读取 GPU 信息相对复杂一些,通常需要借助第三方库,比如OpenHardwareMonitor。首先通过 NuGet 安装OpenHardwareMonitor库。

cs 复制代码
using OpenHardwareMonitor.Hardware;

using System;

class GpuMonitor

{

private Computer computer;

public GpuMonitor()

{

computer = new Computer();

computer.GPUEnabled = true;

computer.Open();

}

public void PrintGpuInfo()

{

foreach (IHardware hardware in computer.Hardware)

{

if (hardware.HardwareType == HardwareType.GpuNvidia || hardware.HardwareType == HardwareType.GpuAmd)

{

hardware.Update();

foreach (ISensor sensor in hardware.Sensors)

{

if (sensor.SensorType == SensorType.Load)

{

Console.WriteLine($"GPU负载: {sensor.Value}%");

}

else if (sensor.SensorType == SensorType.Temperature)

{

Console.WriteLine($"GPU温度: {sensor.Value}℃");

}

}

}

}

}

~GpuMonitor()

{

computer.Close();

}

}

在Main方法中调用:

复制代码
cs 复制代码
GpuMonitor gpuMonitor = new GpuMonitor();

gpuMonitor.PrintGpuInfo();

三、获取屏幕大小

在 C# 中,可以使用System.Windows.Forms.Screen类来获取屏幕相关信息,包括屏幕大小。

cs 复制代码
using System;

using System.Windows.Forms;

class ScreenInfo

{

public static void GetScreenSize()

{

Screen primaryScreen = Screen.PrimaryScreen;

Console.WriteLine($"屏幕宽度: {primaryScreen.Bounds.Width} 像素");

Console.WriteLine($"屏幕高度: {primaryScreen.Bounds.Height} 像素");

}

}

在Main方法中调用ScreenInfo.GetScreenSize()即可获取屏幕大小信息。

四、总结

通过以上方法,我们利用 C# 实现了监控键盘、读取 CPU 和 GPU 资源信息以及获取屏幕大小的功能。这些功能在系统性能分析、特殊输入处理以及图形界面适配等方面都有着重要的应用。在实际开发中,大家可以根据具体需求对这些功能进行拓展和优化。如果在实践过程中遇到问题或者有更好的实现思路,欢迎在评论区交流分享。

相关推荐
许苑向上33 分钟前
Java八股文(下)
java·开发语言
菜鸟一枚在这38 分钟前
深入解析设计模式之单例模式
开发语言·javascript·单例模式
独孤求败Ace41 分钟前
第44天:Web开发-JavaEE应用&反射机制&类加载器&利用链&成员变量&构造方法&抽象方法
java·开发语言
计算机-秋大田1 小时前
基于Spring Boot的农产品智慧物流系统设计与实现(LW+源码+讲解)
java·开发语言·spring boot·后端·spring·课程设计
matlabgoodboy1 小时前
Matlab代编电气仿真电力电子电机控制自动化新能源微电网储能能量
开发语言·matlab·自动化
镰圈量化1 小时前
当电脑上有几个python版本Vscode选择特定版本python
开发语言·vscode·python
背太阳的牧羊人2 小时前
RAG检索中使用一个 长上下文重排序器(Long Context Reorder) 对检索到的文档进行进一步的处理和排序,优化输出顺序
开发语言·人工智能·python·langchain·rag
ITPUB-微风2 小时前
美团MTSQL特性解析:技术深度与应用广度的完美结合
java·服务器·开发语言
Want5952 小时前
C/C++跳动的爱心
c语言·开发语言·c++
水瓶丫头站住2 小时前
Qt中QDockWidget的使用方式
开发语言·qt