C#實現系統(tǒng)信息監(jiān)控與獲取功能
前言
在 C# 開發(fā)的眾多應用場景中,獲取系統(tǒng)信息以及監(jiān)控用戶操作有著廣泛的用途。比如在系統(tǒng)性能優(yōu)化工具中,需要實時讀取 CPU、GPU 資源信息;在一些特殊的輸入記錄程序里,可能會涉及到鍵盤監(jiān)控;而在圖形界面開發(fā)中,獲取屏幕大小是基礎操作。本文將詳細介紹如何使用 C# 來實現這些功能,助力大家在開發(fā)中更好地與系統(tǒng)底層進行交互。
一、C# 監(jiān)控鍵盤
1. 原理與實現思路
在 Windows 系統(tǒng)下,可以通過 Windows API 來實現鍵盤監(jiān)控。需要使用SetWindowsHookEx函數來設置一個鉤子,當鍵盤事件發(fā)生時,系統(tǒng)會調用我們定義的回調函數來處理這些事件。
2. 代碼實現
首先,需要引入System.Runtime.InteropServices命名空間,以便調用 Windows API。
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()來開始監(jiān)控鍵盤,調用KeyboardMonitor.StopMonitoring()停止監(jiān)控。
二、讀取 CPU、GPU 資源信息
1. 使用 PerformanceCounter 讀取 CPU 信息
PerformanceCounter類是.NET 框架提供的用于讀取系統(tǒng)性能計數器的工具。通過它可以方便地獲取 CPU 使用率等信息。
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方法中使用如下:
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庫。
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方法中調用:
GpuMonitor gpuMonitor = new GpuMonitor(); gpuMonitor.PrintGpuInfo();
三、獲取屏幕大小
在 C# 中,可以使用System.Windows.Forms.Screen類來獲取屏幕相關信息,包括屏幕大小。
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# 實現了監(jiān)控鍵盤、讀取 CPU 和 GPU 資源信息以及獲取屏幕大小的功能。這些功能在系統(tǒng)性能分析、特殊輸入處理以及圖形界面適配等方面都有著重要的應用。在實際開發(fā)中,大家可以根據具體需求對這些功能進行拓展和優(yōu)化。
以上就是C#實現系統(tǒng)信息監(jiān)控與獲取功能的詳細內容,更多關于C#系統(tǒng)信息監(jiān)控與獲取的資料請關注腳本之家其它相關文章!
相關文章
C#解決多IfElse判斷語句和Switch語句問題的方法分享
這篇文章主要為大家介紹C#如何使用設計模式中的策略模式和委托來解決多個IfElse判斷語句和Switch語句,這種替換方式在其他語言也一樣可以做到,感興趣的可以了解一下2022-12-12

