Сервис автоматического выхода из системы в приложении wpf

1

Я пытаюсь создать службу автоматического выхода из системы в решении wpf, которое перечисляет использование клавиатуры и мыши. В настоящий момент я использую этот код (см. Ниже). Но это не действует ни на какие окна, кроме основного. Существуют ли другие способы справиться с этим без привязки к главному окну?

 public AutoLogOffService(
            System.Windows.Window applicationWindow,
            IUserProfileManager userProfileManager,
            IDefaultUserDataProvider defaultUserDataProvider,
            IEventAggregator eventAggregator,
            int inactivityInterval)
        {
            _userProfileManager = userProfileManager;
            _defaultUser = defaultUserDataProvider.GetDefaultUser();

            _lastActivity = DateTime.Now;

            var timer = new Timer(1000);
            timer.Elapsed += (sender, args) =>
            {
                //report
                if (DisableAutoLogout)
                {
                    eventAggregator.Publish<ILogOffServiceTimeRemaining>(x =>
                    {
                        x.Percent = 100;
                        x.Seconds = inactivityInterval * 60;
                        x.AutoLogOffDisabled = true;
                    });
                }
                else
                {
                    var remainingSeconds = Convert.ToInt32((_lastActivity.AddMinutes(inactivityInterval) - DateTime.Now).TotalSeconds);
                    remainingSeconds = remainingSeconds < 0 ? 0 : remainingSeconds;
                    var remainingPercent = (int)((double)remainingSeconds / (inactivityInterval * 60) * 100);

                    eventAggregator.Publish<ILogOffServiceTimeRemaining>(x =>
                    {
                        x.Percent = remainingPercent;
                        x.Seconds = remainingSeconds;
                    });
                }

                if (DisableAutoLogout == false && _userProfileManager.CurrentUser != _defaultUser
                    && _lastActivity < DateTime.Now - TimeSpan.FromMinutes(inactivityInterval))
                {
                    DispatcherHelper.SafeInvoke(() => _userProfileManager.CurrentUser = _defaultUser);
                }
            };

            timer.Start();

            var windowSpecificOSMessageListener = HwndSource.FromHwnd(new WindowInteropHelper(applicationWindow).Handle);
            if (windowSpecificOSMessageListener != null)
            {
                windowSpecificOSMessageListener.AddHook((IntPtr hwnd, int msg, IntPtr param, IntPtr lParam, ref bool handled) =>
                {
                    //  Listening OS message to test whether it is a user activity
                    if ((msg >= 0x0200 && msg <= 0x020A) || (msg <= 0x0106 && msg >= 0x00A0) || msg == 0x0021)
                    {
                        //Debug.WriteLine("Message {0:X}", msg);
                        _lastActivity = DateTime.Now;
                    }
                    return IntPtr.Zero;
                });
            }
        }
Теги:
wpf

1 ответ

1
Лучший ответ

Вы можете получить доступ к каждому Window в приложении WPF с помощью объекта Application.Current.Windows:

foreach (Window window in Application.Current.Windows)
{
    AutoLogOffService autoLogOffService = new AutoLogOffService(window);
}

Вы также можете просто выбрать пользовательское Window определенного типа

foreach (CustomWindow window in Application.Current.Windows.OfType<CustomWindow>())
{
    AutoLogOffService autoLogOffService = new AutoLogOffService(window);
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню