C#OpenProcess返回错误1150

问题描述 投票:0回答:1

这是我为打开流程而编写的代码:

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern UIntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(UIntPtr hObject);

        private const uint PROCESS_QUERY_INFORMATION = 0x0400;

        public static void processInfo() {
            uint PID = 3144;
            UIntPtr handle = UIntPtr.Zero;
            handle = OpenProcess(PROCESS_QUERY_INFORMATION, false, PID);
            Console.WriteLine(Marshal.GetLastWin32Error());
            Console.WriteLine(handle);
            if (!handle.Equals(UIntPtr.Zero)) {
                CloseHandle(handle);
            }
        }

Marshal.GetLastWin32Error()为任何进程返回错误1150。来自MSDN:

“ERROR_OLD_WIN_VERSION:指定的程序需要较新版本的Windows。”

我在Visual Studio 2015 Community Edition中的Windows 2008 R2中运行此代码。目标框架在项目设置中设置为“.NET Framework 4.5.2”。

此外,似乎OpenProcess仍然能够完成其工作,因为返回的句柄不为零。我应该关注这个错误吗?

c# winapi dllimport
1个回答
2
投票

从文档:

如果函数成功,则返回值是指定进程的打开句柄。

如果函数失败,则返回值为NULL。要获取扩展错误信息,请调用GetLastError

请注意,唯一提到的调用GetLastError的方法是函数是否失败。这由返回值表示。仅在函数失败时检查错误代码,在该情况下它只有一个有意义的值。您的错误在于您无条件地检查错误代码。

handle = OpenProcess(...);
if (handle == UIntPtr.Zero)
    // only now call Marshal.GetLastWin32Error

另请注意,分配handle两次是没有意义的。你写了:

UIntPtr handle = UIntPtr.Zero;
handle = OpenProcess(...);

当然编译器警告说这没有意义,没有使用分配给handle的值。您的代码有点类似于:

int i = 1;
i = 2;

我相信你永远不会这样做。你的代码应该是:

UIntPtr handle = OpenProcess(...);
© www.soinside.com 2019 - 2024. All rights reserved.