从WindowsService如何可以找到当前登录的用户从C#? [英] From WindowsService how can I find currently logged in user from C#?

查看:343
本文介绍了从WindowsService如何可以找到当前登录的用户从C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在管理员帐户下运行Windows服务,我想找出谁是当前登录用户。这将是从帐户WindowService不同的是,目前正在运行。 ?
有没有简单的方法来从C#得到它

I am running windows service under Administrator account and I would like to find out who is the currently logged in user. It will be different from account WindowService is currently running under. Is there any easy way to get it from c#?

这不是:
System.Security.Principal.WindowsIdentity.GetCurrent()
既不
System.Environment.UserName

It is not: System.Security.Principal.WindowsIdentity.GetCurrent() neither System.Environment.UserName

感谢

修改

我感兴趣的是谁目前与控制台会话登录。感谢jadarnel27

I am interested who is currently logged in with Console session. thanks jadarnel27

我在其他远程会话不感兴趣,因为这不是我的情况。

I am not interested in other remote sessions since this is not my case scenario.

推荐答案

1)应该能够给你登录的用户的当前的列表,包括RDC。

1) Cassia should be able to give you a list of currently logged in users including RDC.

foreach (ITerminalServicesSession sess in new TerminalServicesManager().GetSessions())
{
    // sess.SessionId
    // sess.UserName
}

2)WMI (SO 答案

2) WMI (SO answer)

Select * from Win32_LogonSession

3)的PInvoke到 WTSEnumerateSessions

3) PInvoke to WTSEnumerateSessions

4)列举的explorer.exe的所有实例,并得到使用的PInvoke(的 OpenProcessHandle )。

4) Enumerate all instances of "explorer.exe" and get the owner using PInvoke (OpenProcessHandle).

Process[] processes = Process.GetProcessesByName("explorer");

这是一个有点哈克。 WMI 的也可用于这一点。

This is a bit hacky. WMI can also be used for this.

这可能是设置的 Winmgmt的为您服务的依赖,如果你决定去与使用WMI的解决方案。

It might be a good idea to set winmgmt as a dependency for your service if you decided to go with solution that uses WMI.

这篇关于从WindowsService如何可以找到当前登录的用户从C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆