I'm trying to create a auto logout service in a wpf solution, which is listing to the keyboard and mouse usage. At the moment im using this code( see below ). But it does not take in effect to any windows other than the main. Are there other ways to handle this without being attached to the mainwindow?
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;
});
}
}