【问题标题】:System Idle Detection in windows applicationWindows 应用程序中的系统空闲检测
【发布时间】:2021-08-12 21:18:54
【问题描述】:

我想要一个应用程序,如果用户在某些分钟内不活动,则显示消息。

我用谷歌搜索了它并得到了解决方案,但对我来说很难理解,我不知道如何使用该代码,

如果有人向我提供一些文章,该文章显示了逐步检测用户不活动并在 Windows 应用程序 c# 中显示消息的过程,我们将不胜感激。

【问题讨论】:

    标签: c# wpf windows desktop-application


    【解决方案1】:

    使用 Windows API 调用 GetLastInputInfo() 很容易做到这一点,前提是您可以这样做。这是它的示例包装类:

    public sealed class UserActivityMonitor
    {
        public UserActivityMonitor()
        {
            _lastInputInfo.CbSize = Marshal.SizeOf(_lastInputInfo);
        }
    
        /// <summary>Determines the time of the last user activity (any mouse activity or key press).</summary>
        /// <returns>The time of the last user activity.</returns>
    
        public DateTime LastActivity => DateTime.Now - this.InactivityPeriod;
    
        /// <summary>The amount of time for which the user has been inactive (no mouse activity or key press).</summary>
    
        public TimeSpan InactivityPeriod
        {
            get
            {
                GetLastInputInfo(ref _lastInputInfo);
                uint elapsedMilliseconds = (uint)Environment.TickCount - _lastInputInfo.DwTime;
                elapsedMilliseconds = Math.Min(elapsedMilliseconds, int.MaxValue);
                return TimeSpan.FromMilliseconds(elapsedMilliseconds);
            }
        }
    
        /// <summary>Struct used by Windows API function GetLastInputInfo()</summary>
        struct LastInputInfo
        {
            public int  CbSize;
            public uint DwTime;
        }
    
        [DllImport("user32.dll")]
        [DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
        [return: MarshalAs(UnmanagedType.Bool)]
    
        static extern bool GetLastInputInfo(ref LastInputInfo plii);
    
        LastInputInfo _lastInputInfo;
    }
    

    要使用它,只需创建类的一个实例并定期检查InactivityPeriod 属性(例如,使用Timer)。

    【讨论】:

    • 我理解代码,但是我必须把这段代码放在哪里,我的意思是在 program.cs 文件或其他地方。
    • 您只需将其添加到您的应用程序的单独代码文件中的新类中,就像您编写的任何其他类一样。
    猜你喜欢
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2015-09-15
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多