-4

我尝试使用该OpenProcess函数获取正在运行的进程的句柄。但是,当检查错误代码时,我得到一个错误代码 6 (ERROR_INVALID_HANDLE)。

这是一个简化的示例:

using System;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace Test
{
    class TestClass
    {
        [DllImport("kernel32.dll")]
        static extern uint GetLastError();

        [DllImport("kernel32.dll")]
        public static extern IntPtr OpenProcess(int dwDesiredAccess,
               bool bInheritHandle, int dwProcessId);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool WriteProcessMemory(int hProcess, int lpBaseAddress,
              byte[] lpBuffer, int dwSize, ref int lpNumberOfBytesWritten);

        static void Main() 
        {
            var process = Process.GetProcessesByName("Sample")[0];
            var processHandle = OpenProcess(0x001F0FFF, false, process.Id);    
            Console.WriteLine(GetLastError());

            int bytesRead = 0;
            byte[] buffer = BitConverter.GetBytes(1095090201);

            WriteProcessMemory(
                (int)processHandle,
                0x21F3CAAC,
                buffer,
                buffer.Length, 
                ref bytesRead);

            Console.ReadKey();
        }
    }
}
}

我不确定为什么它不起作用。它只返回错误代码 6。有什么建议吗?

我不知何故感觉这是因为我正在访问的程序,但其他一切都运行良好并且没有返回任何其他错误。

4

1 回答 1

1

您需要改进错误检查。在请求最后一个错误之前,您需要先检查返回码是否OpenProcess为空。请注意,DllImport需要SetLastError将其设置为 true 才能正常工作,并且GetLastError 不应使用

[DllImport("kernel32.dll", SetLastError=true)]
public static extern IntPtr OpenProcess(int dwDesiredAccess,
       bool bInheritHandle, int dwProcessId);

processHandle = OpenProcess(0x001F0FFF, false, process.Id); 
if (processHandle == IntPtr.Zero)
{
    Console.WriteLine(Marshal.GetLastWin32Error());
}

理想情况下,您将从本机错误代码创建托管异常。这样做的好处是您可以使用标准的 .NET 异常处理,并且您可以将错误代码和文本描述很好地包含在异常中:

processHandle = OpenProcess(0x001F0FFF, false, process.Id); 
if (processHandle == IntPtr.Zero)
{
    // calls Marhal.GetLastWin32Error and GetErrorMessage under the hood
    throw new Win32Exception();
}

当然,完成后别忘了打电话CloseHandle

于 2015-12-08T12:42:16.897 回答