c# - WTSQueryUserToken 在 C# 的 Windows 7 上总是抛出 "An attempt was made to reference a token that does not exist"

标签 c# windows service pinvoke elevation

我正在尝试从 Windows 7 上的 Windows 服务启动进程。

这是我获取用户 token 的代码。

uint sessionId = Kernel32.WTSGetActiveConsoleSessionId();
var userTokenPtr = new IntPtr();
if (!WtsApi32.WTSQueryUserToken(sessionId, out userTokenPtr))
{
    int lastError = Marshal.GetLastWin32Error();
    throw new Win32Exception(lastError);
}

这些是 DllImport 语句:

public class Kernel32
{
    [DllImport("kernel32.dll", EntryPoint = "WTSGetActiveConsoleSessionId")]
    public static extern uint WTSGetActiveConsoleSessionId();
}

public class WtsApi32
{
    [DllImport("Wtsapi32.dll", EntryPoint = "WTSQueryUserToken")]
    public static extern bool WTSQueryUserToken(UInt32 sessionId, out IntPtr phToken);
}

我从这个答案中取出代码并按原样复制它:https://stackoverflow.com/a/11266955/410075

它总是抛出 Win32Exception 并显示消息“试图引用不存在的标记”。这是数据:sessionId = 1 和 lastError = 1008。

我尝试将其运行为:

  • 调试过程(使用 Visual Studio 托管过程)
  • 调试过程(没有 Visual Studio 托管过程)
  • 管理员用户
  • 高级管理员用户
  • Windows 服务。
  • 以管理员用户身份登录的 Windows 服务。
  • 当我向上帝、撒旦、Buddah 和 Rael 祈祷时。

我还为可执行文件创建了一个需要管理员提升的 list 。

没有任何效果,它总是抛出完全相同的异常。我没有想法......

最佳答案

您必须将 SetLastError = true 添加到 WTSQueryUserToken 的 DllImport 属性,否则,GetLastWin32Error没有意义。

此外,您必须在 LocalSystem 帐户的上下文中运行此代码 as stipulated in the documentation (不仅仅是“管理员用户”):

Obtains the primary access token of the logged-on user specified by the session ID. To call this function successfully, the calling application must be running within the context of the LocalSystem account and have the SE_TCB_NAME privilege.

关于c# - WTSQueryUserToken 在 C# 的 Windows 7 上总是抛出 "An attempt was made to reference a token that does not exist",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16621448/

相关文章:

windows - 如果一个进程建立了多个 PostgreSQL 连接并在没有关闭它们的情况下终止,会发生什么?

c - 错误 C2275 : illegal use of this type as an expression

Android:让通知在手机重启后持续存在

c# - 为什么 "ref"关键字与 System.ServiceModel.Channels.Message 一起使用?

c# - 如何为批量插入参数设置值?

Python命令在命令提示符下不起作用

android - 如何将数据从 Activity 传递到正在运行的服务

c# - nuget 无法在通用应用程序中将引用添加到 Windows Phone 8.1 项目中

C#:如何在一个文件中读取 'éóú' 和 öäü 等字符?

windows - Windows 上的文件是否具有编码属性?