# ============================================
# Windows API 在 PowerShell 中的使用示例
# ============================================

# ============================================
# 方法 1: 直接调用 Windows API (P/Invoke)
# ============================================

# 定义 Windows API 函数和结构体
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Text;

public class Win32API {
    // 常量定义
    public const uint TH32CS_SNAPPROCESS = 0x00000002;
    public const uint PROCESS_ALL_ACCESS = 0x001F0FFF;
    public const uint PROCESS_QUERY_INFORMATION = 0x0400;
    
    // PROCESSENTRY32 结构体
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public struct PROCESSENTRY32 {
        public uint dwSize;
        public uint cntUsage;
        public uint th32ProcessID;
        public IntPtr th32DefaultHeapID;
        public uint th32ModuleID;
        public uint cntThreads;
        public uint th32ParentProcessID;
        public int pcPriClassBase;
        public uint dwFlags;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szExeFile;
    }
    
    // 函数声明
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
    
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
    
    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    public static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool CloseHandle(IntPtr hObject);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
    
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool ReadProcessMemory(
        IntPtr hProcess,
        IntPtr lpBaseAddress,
        [Out] byte[] lpBuffer,
        int dwSize,
        out IntPtr lpNumberOfBytesRead
    );
    
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern bool WriteProcessMemory(
        IntPtr hProcess,
        IntPtr lpBaseAddress,
        byte[] lpBuffer,
        int nSize,
        out IntPtr lpNumberOfBytesWritten
    );
}
"@

# ============================================
# 功能实现:枚举所有进程
# ============================================
function Get-AllProcesses {
    $processes = @()
    $hSnapshot = [Win32API]::CreateToolhelp32Snapshot([Win32API]::TH32CS_SNAPPROCESS, 0)
    
    if ($hSnapshot -eq [IntPtr]::Zero) {
        Write-Error "无法创建进程快照"
        return $processes
    }
    
    $pe = New-Object Win32API+PROCESSENTRY32
    $pe.dwSize = [System.Runtime.InteropServices.Marshal]::SizeOf($pe)
    
    if ([Win32API]::Process32First($hSnapshot, [ref]$pe)) {
        do {
            $processes += [PSCustomObject]@{
                PID = $pe.th32ProcessID
                Name = $pe.szExeFile
            }
        } while ([Win32API]::Process32Next($hSnapshot, [ref]$pe))
    }
    
    [Win32API]::CloseHandle($hSnapshot) | Out-Null
    return $processes
}

# ============================================
# 功能实现:根据名称查找进程
# ============================================
function Find-ProcessByName {
    param([string]$ProcessName)
    
    $allProcesses = Get-AllProcesses
    $matches = $allProcesses | Where-Object { $_.Name -eq $ProcessName }
    return $matches.PID
}

# ============================================
# 功能实现:检查进程是否运行
# ============================================
function Test-ProcessRunning {
    param([uint32]$ProcessId)
    
    $hProcess = [Win32API]::OpenProcess(
        [Win32API]::PROCESS_QUERY_INFORMATION,
        $false,
        $ProcessId
    )
    
    if ($hProcess -ne [IntPtr]::Zero) {
        [Win32API]::CloseHandle($hProcess) | Out-Null
        return $true
    }
    
    return $false
}

# ============================================
# 功能实现:读取进程内存
# ============================================
function Read-ProcessMemory {
    param(
        [uint32]$ProcessId,
        [IntPtr]$Address,
        [int]$Size = 4
    )
    
    $hProcess = [Win32API]::OpenProcess(
        [Win32API]::PROCESS_ALL_ACCESS,
        $false,
        $ProcessId
    )
    
    if ($hProcess -eq [IntPtr]::Zero) {
        Write-Error "无法打开进程 (可能需要管理员权限)"
        return $null
    }
    
    $buffer = New-Object byte[] $Size
    $bytesRead = [IntPtr]::Zero
    
    $success = [Win32API]::ReadProcessMemory(
        $hProcess,
        $Address,
        $buffer,
        $Size,
        [ref]$bytesRead
    )
    
    [Win32API]::CloseHandle($hProcess) | Out-Null
    
    if ($success) {
        return $buffer
    }
    
    return $null
}

# ============================================
# 使用示例
# ============================================

Write-Host "=== 枚举所有进程 ===" -ForegroundColor Green
$allProcs = Get-AllProcesses
$allProcs | Select-Object -First 10 | Format-Table

Write-Host "`n=== 查找 notepad.exe 进程 ===" -ForegroundColor Green
$notepadPids = Find-ProcessByName "notepad.exe"
if ($notepadPids) {
    Write-Host "找到进程: $notepadPids"
} else {
    Write-Host "未找到 notepad.exe"
}

Write-Host "`n=== 检查进程是否运行 ===" -ForegroundColor Green
if ($notepadPids) {
    $isRunning = Test-ProcessRunning $notepadPids[0]
    Write-Host "进程 $($notepadPids[0]) 是否运行: $isRunning"
}