在C#中获取当前活动窗口的图标可以通过以下步骤实现:
System.Runtime.InteropServices
命名空间,以便使用Windows API函数。GetForegroundWindow
函数获取当前活动窗口的句柄。GetWindowThreadProcessId
函数获取当前活动窗口所属进程的ID。OpenProcess
函数打开进程,获取进程的句柄。GetModuleFileNameEx
函数获取进程的可执行文件路径。ExtractIconEx
函数获取进程的图标。DestroyIcon
函数释放图标资源。下面是一个示例代码:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
[DllImport("kernel32.dll")]
private static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("psapi.dll")]
private static extern int GetModuleFileNameEx(IntPtr hProcess, IntPtr hModule, out string lpFilename, int nSize);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern bool DestroyIcon(IntPtr handle);
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern int ExtractIconEx(string lpszFile, int nIconIndex, out IntPtr phiconLarge, out IntPtr phiconSmall, int nIcons);
static void Main()
{
IntPtr hWnd = GetForegroundWindow();
int processId;
GetWindowThreadProcessId(hWnd, out processId);
IntPtr hProcess = OpenProcess(0x0410, false, processId);
string fileName;
GetModuleFileNameEx(hProcess, IntPtr.Zero, out fileName, 1024);
IntPtr hIconLarge, hIconSmall;
ExtractIconEx(fileName, 0, out hIconLarge, out hIconSmall, 1);
Icon icon = Icon.FromHandle(hIconSmall);
// 使用图标进行操作...
DestroyIcon(hIconLarge);
DestroyIcon(hIconSmall);
}
}
这段代码通过调用Windows API函数获取当前活动窗口的句柄和进程ID,然后打开进程并获取进程的可执行文件路径。最后,使用ExtractIconEx
函数获取进程的图标,并将其转换为Icon
对象进行操作。
请注意,这只是一个简单的示例代码,实际应用中可能需要进行错误处理和资源释放等操作。另外,获取到的图标可能是多个图标中的一个,可以根据需要进行调整。
腾讯技术开放日
serverless days
腾讯技术开放日
Elastic 中国开发者大会
云+社区技术沙龙[第10期]
云+社区技术沙龙[第6期]
腾讯云GAME-TECH沙龙
云+社区技术沙龙[第9期]
领取专属 10元无门槛券
手把手带您无忧上云