命名空间 'Windows.Win32' 中不存在类型或命名空间名称 'System'

The type or namespace name 'System' does not exist in the namespace 'Windows.Win32'

我有一个 .Net5.0-windows 项目,其中我有以下功能:

public static void EnableDisplayTimeout()
{
     PInvoke.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
}

这需要使用智能感知识别的 Windows.Win32.System.Power,为我提供正确的导入,然后一切似乎都井井有条。当我尝试构建项目时,它因错误 Error CS0234: The type or namespace name 'System' does not exist in the namespace 'Windows.Win32' (are you missing an assembly reference?) (2, 21).

而失败

我不确定我是否理解这个问题。我是 .NET 的新手,所以我不确定我是否了解 VS 的内部工作原理。我正在使用 VS 2019、CsWin32 NuGet 和 ReSharper 2021.1.3。我已经尝试禁用 ReSharper,但问题仍然存在。我是否遗漏了一些配置步骤?

您确定 Windows.Win32 命名空间?也许 Microsoft.Win32 should be? Or Windows.System.Power?或者什么都不是,因为 SetThreadExecutionState 在那里不存在并且由 DllImport:

kernel32.dll 中获取

PInvoke.cs:

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp
{
    public class PInvoke
    {
        [Flags]
        public enum EXECUTION_STATE : uint
        {
            ES_AWAYMODE_REQUIRED = 0x00000040,
            ES_CONTINUOUS = 0x80000000,
            ES_DISPLAY_REQUIRED = 0x00000002,
            ES_SYSTEM_REQUIRED = 0x00000001
        }

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
    }
}

和用法:

Program.cs:

using System;

namespace ConsoleApp
{
    public class Program
    {
        static void Main()
        {
            var executionState = PInvoke.SetThreadExecutionState(PInvoke.EXECUTION_STATE.ES_CONTINUOUS);
            Console.WriteLine(executionState);
            Console.ReadKey();
        }
    }
}

原来这是一个 sdk 错误。我升级到 .net sdk 6,问题消失了。

根据这些找到解决方案:
https://github.com/microsoft/CsWin32/issues/7
https://github.com/dotnet/wpf/issues/3404