我正在尝试从 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/