以编程方式确定锁定工作站的持续时间?


111

如何用代码确定机器被锁定了多长时间?

也欢迎使用C#之外的其他想法。


我喜欢Windows服务的想法(并已接受它)是为了简洁和整洁,但不幸的是,我认为在这种情况下,它不会对我有用。我想在工作场所而不是在家(或者我想在家中)上在工作站上运行它,但是出于国防部的考虑,它很难解决。实际上,这就是我自己推出自己的原因的一部分。

无论如何,我都会写出来,看看它是否有效。感谢大家!

Answers:


138

我以前没有找到过,但是从任何应用程序中,您都可以连接SessionSwitchEventHandler。显然,您的应用程序将需要运行,但前提是:

Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);

void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
    if (e.Reason == SessionSwitchReason.SessionLock)
    { 
        //I left my desk
    }
    else if (e.Reason == SessionSwitchReason.SessionUnlock)
    { 
        //I returned to my desk
    }
}

3
在Windows 7 x64和Windows 10 x64上测试100%。
Contango

哇,棒极了!没有错误没有例外,干净整洁!
Mayer Spitzer

这是正确的方法。根据Microsoft的这篇文章,“没有可以调用的功能来确定工作站是否被锁定。” 必须使用SessionSwitchEventHandler对其进行监视。
JonathanDavidArndt

35

我将创建一个Windows Service(Visual Studio 2005项目类型)来处理OnSessionChange事件,如下所示:

protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
    if (changeDescription.Reason == SessionChangeReason.SessionLock)
    { 
        //I left my desk
    }
    else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)
    { 
        //I returned to my desk
    }
}

此时,您将如何记录活动以及如何记录活动取决于您,但是Windows服务可以快速,轻松地访问Windows事件,例如启动,关闭,登录/注销,以及锁定和解锁事件。


18

下面的解决方案使用Win32 API。工作站锁定时调用OnSessionLock,解锁时调用OnSessionUnlock。

[DllImport("wtsapi32.dll")]
private static extern bool WTSRegisterSessionNotification(IntPtr hWnd,
int dwFlags);

[DllImport("wtsapi32.dll")]
private static extern bool WTSUnRegisterSessionNotification(IntPtr
hWnd);

private const int NotifyForThisSession = 0; // This session only

private const int SessionChangeMessage = 0x02B1;
private const int SessionLockParam = 0x7;
private const int SessionUnlockParam = 0x8;

protected override void WndProc(ref Message m)
{
    // check for session change notifications
    if (m.Msg == SessionChangeMessage)
    {
        if (m.WParam.ToInt32() == SessionLockParam)
            OnSessionLock(); // Do something when locked
        else if (m.WParam.ToInt32() == SessionUnlockParam)
            OnSessionUnlock(); // Do something when unlocked
    }

    base.WndProc(ref m);
    return;
}

void OnSessionLock() 
{
    Debug.WriteLine("Locked...");
}

void OnSessionUnlock() 
{
    Debug.WriteLine("Unlocked...");
}

private void Form1Load(object sender, EventArgs e)
{
    WTSRegisterSessionNotification(this.Handle, NotifyForThisSession);
}

// and then when we are done, we should unregister for the notification
//  WTSUnRegisterSessionNotification(this.Handle);

1
如果您发现SessionSwitch事件(来自其他答案)没有触发(例如,您的应用程序禁止了该事件),则这是一个不错的选择。
kad81 2015年

对于将来的读者...我想想这里的替代内容来自System.Windows.Forms.Form,因为您可能会编写这样的类:public class Form1:System.Windows.Forms.Form
granadaCoder

这对我的作品的时候SystemEvents.SessionSwitch
DCOPTimDowd

5

我知道这是一个老问题,但是我找到了一种获取给定会话的锁定状态的方法。

我在这里找到答案但是它是用C ++编写的,所以我尽可能地将其翻译为C#以获取“锁定状态”。

因此,这里去:

static class SessionInfo {
    private const Int32 FALSE = 0;

    private static readonly IntPtr WTS_CURRENT_SERVER = IntPtr.Zero;

    private const Int32 WTS_SESSIONSTATE_LOCK = 0;
    private const Int32 WTS_SESSIONSTATE_UNLOCK = 1;

    private static bool _is_win7 = false;

    static SessionInfo() {
        var os_version = Environment.OSVersion;
        _is_win7 = (os_version.Platform == PlatformID.Win32NT && os_version.Version.Major == 6 && os_version.Version.Minor == 1);
    }

    [DllImport("wtsapi32.dll")]
    private static extern Int32 WTSQuerySessionInformation(
        IntPtr hServer,
        [MarshalAs(UnmanagedType.U4)] UInt32 SessionId,
        [MarshalAs(UnmanagedType.U4)] WTS_INFO_CLASS WTSInfoClass,
        out IntPtr ppBuffer,
        [MarshalAs(UnmanagedType.U4)] out UInt32 pBytesReturned
    );

    [DllImport("wtsapi32.dll")]
    private static extern void WTSFreeMemoryEx(
        WTS_TYPE_CLASS WTSTypeClass,
        IntPtr pMemory,
        UInt32 NumberOfEntries
    );

    private enum WTS_INFO_CLASS {
        WTSInitialProgram = 0,
        WTSApplicationName = 1,
        WTSWorkingDirectory = 2,
        WTSOEMId = 3,
        WTSSessionId = 4,
        WTSUserName = 5,
        WTSWinStationName = 6,
        WTSDomainName = 7,
        WTSConnectState = 8,
        WTSClientBuildNumber = 9,
        WTSClientName = 10,
        WTSClientDirectory = 11,
        WTSClientProductId = 12,
        WTSClientHardwareId = 13,
        WTSClientAddress = 14,
        WTSClientDisplay = 15,
        WTSClientProtocolType = 16,
        WTSIdleTime = 17,
        WTSLogonTime = 18,
        WTSIncomingBytes = 19,
        WTSOutgoingBytes = 20,
        WTSIncomingFrames = 21,
        WTSOutgoingFrames = 22,
        WTSClientInfo = 23,
        WTSSessionInfo = 24,
        WTSSessionInfoEx = 25,
        WTSConfigInfo = 26,
        WTSValidationInfo = 27,
        WTSSessionAddressV4 = 28,
        WTSIsRemoteSession = 29
    }

    private enum WTS_TYPE_CLASS {
        WTSTypeProcessInfoLevel0,
        WTSTypeProcessInfoLevel1,
        WTSTypeSessionInfoLevel1
    }

    public enum WTS_CONNECTSTATE_CLASS {
        WTSActive,
        WTSConnected,
        WTSConnectQuery,
        WTSShadow,
        WTSDisconnected,
        WTSIdle,
        WTSListen,
        WTSReset,
        WTSDown,
        WTSInit
    }

    public enum LockState {
        Unknown,
        Locked,
        Unlocked
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct WTSINFOEX {
        public UInt32 Level;
        public UInt32 Reserved; /* I have observed the Data field is pushed down by 4 bytes so i have added this field as padding. */
        public WTSINFOEX_LEVEL Data;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct WTSINFOEX_LEVEL {
        public WTSINFOEX_LEVEL1 WTSInfoExLevel1;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct WTSINFOEX_LEVEL1 {
        public UInt32 SessionId;
        public WTS_CONNECTSTATE_CLASS SessionState;
        public Int32 SessionFlags;

        /* I can't figure out what the rest of the struct should look like but as i don't need anything past the SessionFlags i'm not going to. */

    }

    public static LockState GetSessionLockState(UInt32 session_id) {
        IntPtr ppBuffer;
        UInt32 pBytesReturned;

        Int32 result = WTSQuerySessionInformation(
            WTS_CURRENT_SERVER,
            session_id,
            WTS_INFO_CLASS.WTSSessionInfoEx,
            out ppBuffer,
            out pBytesReturned
        );

        if (result == FALSE)
            return LockState.Unknown;

        var session_info_ex = Marshal.PtrToStructure<WTSINFOEX>(ppBuffer);

        if (session_info_ex.Level != 1)
            return LockState.Unknown;

        var lock_state = session_info_ex.Data.WTSInfoExLevel1.SessionFlags;
        WTSFreeMemoryEx(WTS_TYPE_CLASS.WTSTypeSessionInfoLevel1, ppBuffer, pBytesReturned);

        if (_is_win7) {
            /* Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/ee621019(v=vs.85).aspx
                * Windows Server 2008 R2 and Windows 7:  Due to a code defect, the usage of the WTS_SESSIONSTATE_LOCK
                * and WTS_SESSIONSTATE_UNLOCK flags is reversed. That is, WTS_SESSIONSTATE_LOCK indicates that the
                * session is unlocked, and WTS_SESSIONSTATE_UNLOCK indicates the session is locked.
                * */
            switch (lock_state) {
                case WTS_SESSIONSTATE_LOCK:
                    return LockState.Unlocked;

                case WTS_SESSIONSTATE_UNLOCK:
                    return LockState.Locked;

                default:
                    return LockState.Unknown;
            }
        }
        else {
            switch (lock_state) {
                case WTS_SESSIONSTATE_LOCK:
                    return LockState.Locked;

                case WTS_SESSIONSTATE_UNLOCK:
                    return LockState.Unlocked;

                default:
                    return LockState.Unknown;
            }
        }
    }
}

注意:上面的代码是从一个更大的项目中提取的,所以如果我错过了一点抱歉。我没有时间测试上面的代码,但计划在一两周后回来检查所有内容。我现在才发布它是因为我不想忘记这样做。


这有效(到目前为止已测试Windows 7)。谢谢,我们在过去几周一直在寻找这个,您的答案已经来不及了!
SteveP '16

1
代码中几乎没有错误:1.- if (session_info_ex.Level != 1)如果条件为true,则不会释放内存。2.如果session_info_ex.Level!= 1,则不应这样做:Marshal.PtrToStructure<WTSINFOEX>(ppBuffer);因为返回缓冲区的大小可能与WTSINFOEX的大小不同
SergeyT

(续)3.不必添加字段,UInt32 Reserved;而应WTSINFOEX_LEVEL1完全定义结构。在这种情况下,编译器将对结构内部的字段进行正确的填充(对齐)。4. WTSFreeMemoryEx此处功能被滥用。WTSFreeMemory必须改为使用。WTSFreeMemoryEx旨在在之后释放内存WTSEnumerateSessionsEx
SergeyT

(已计数)5. CharSet = CharSet.Auto必须在所有属性中使用。
SergeyT

4

如果您有兴趣编写Windows服务以“查找”这些事件,那么topshelf(使编写Windows服务更加容易的库/框架)有一个钩子。

public interface IMyServiceContract
{
    void Start();

    void Stop();

    void SessionChanged(Topshelf.SessionChangedArguments args);
}



public class MyService : IMyServiceContract
{

    public void Start()
    {
    }

    public void Stop()
    {

    }

    public void SessionChanged(SessionChangedArguments e)
    {
        Console.WriteLine(e.ReasonCode);
    }   
}

现在将topshelf服务连接到上面的接口/混凝土的代码

下面的所有内容都是“典型的” topshelf设置...。除了我标记为的两行

/ *这是魔术线* /

这些就是激发SessionChanged方法的原因。

我使用Windows 10 x64进行了测试。我锁定并解锁了机器,并获得了预期的结果。

            IMyServiceContract myServiceObject = new MyService(); /* container.Resolve<IMyServiceContract>(); */


            HostFactory.Run(x =>
            {
                x.Service<IMyServiceContract>(s =>
                {
                    s.ConstructUsing(name => myServiceObject);
                    s.WhenStarted(sw => sw.Start());
                    s.WhenStopped(sw => sw.Stop());
                    s.WhenSessionChanged((csm, hc, chg) => csm.SessionChanged(chg)); /* THIS IS MAGIC LINE */
                });

                x.EnableSessionChanged(); /* THIS IS MAGIC LINE */

                /* use command line variables for the below commented out properties */
                /*
                x.RunAsLocalService();
                x.SetDescription("My Description");
                x.SetDisplayName("My Display Name");
                x.SetServiceName("My Service Name");
                x.SetInstanceName("My Instance");
                */

                x.StartManually(); // Start the service manually.  This allows the identity to be tweaked before the service actually starts

                /* the below map to the "Recover" tab on the properties of the Windows Service in Control Panel */
                x.EnableServiceRecovery(r =>
                {
                    r.OnCrashOnly();
                    r.RestartService(1); ////first
                    r.RestartService(1); ////second
                    r.RestartService(1); ////subsequents
                    r.SetResetPeriod(0);
                });

                x.DependsOnEventLog(); // Windows Event Log
                x.UseLog4Net();

                x.EnableShutdown();

                x.OnException(ex =>
                {
                    /* Log the exception */
                    /* not seen, I have a log4net logger here */
                });
            });                 

我的packages.config提供有关版本的提示:

  <package id="log4net" version="2.0.5" targetFramework="net45" />
  <package id="Topshelf" version="4.0.3" targetFramework="net461" />
  <package id="Topshelf.Log4Net" version="4.0.3" targetFramework="net461" />

或者,如果已经实现并且不隐式创建服务类实例,则可以x.EnableSessionChanged();ServiceSessionChange接口实现结合使用ServiceControl。像x.Service<ServiceImpl>();。您必须ServiceSessionChangeServiceImpl课堂上实施:class ServiceImpl : ServiceControl, ServiceSessionChange
oleksa

3

:这不是答案,而是对蒂莫西·卡特的(贡献)答案,因为到目前为止,我的名声不允许我发表评论。

万一有人尝试了蒂莫西·卡特(Timothy Carter)的答案中的代码,而又没有立即在Windows服务中正常工作,则必须true在服务的构造函数中设置一个属性。只需在构造函数中添加以下行:

CanHandleSessionChangeEvent = true;

并且确保在服务启动后不要设置此属性,否则InvalidOperationException将抛出。


-3

下面是100%工作代码,用于查找PC​​是否已锁定。

在使用此功能之前,请使用命名空间System.Runtime.InteropServices

[DllImport("user32", EntryPoint = "OpenDesktopA", CharSet = CharSet.Ansi,SetLastError = true, ExactSpelling = true)]
private static extern Int32 OpenDesktop(string lpszDesktop, Int32 dwFlags, bool fInherit, Int32 dwDesiredAccess);

[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 CloseDesktop(Int32 hDesktop);

[DllImport("user32", CharSet = CharSet.Ansi,SetLastError = true,ExactSpelling = true)]
private static extern Int32 SwitchDesktop(Int32 hDesktop);

public static bool IsWorkstationLocked()
{
    const int DESKTOP_SWITCHDESKTOP = 256;
    int hwnd = -1;
    int rtn = -1;

    hwnd = OpenDesktop("Default", 0, false, DESKTOP_SWITCHDESKTOP);

    if (hwnd != 0)
    {
        rtn = SwitchDesktop(hwnd);
        if (rtn == 0)
        {
            // Locked
            CloseDesktop(hwnd);
            return true;
        }
        else
        {
            // Not locked
            CloseDesktop(hwnd);
        }
    }
    else
    {
        // Error: "Could not access the desktop..."
    }

    return false;
}

4
在MSDN中检查OpenInputDesktop和GetUserObjectInformation,以获取活动的桌面名称。对于使用Microsoft的desktops.exe实用程序或其他方法在多个桌面中工作的用户,上面的代码并不安全/不好。或者更好的方法是,尝试在活动桌面(SetThreadDesktop)上创建一个窗口,如果可行,则在其上显示您的UI。如果不是,那么它是受保护的/特殊的桌面,所以不要。
eselk 2012年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.