I’m building an AvaloniaUI app and would like to auto log off users after the app is idle for a period of time. I’ve found a great solution to this for WPF here:
https://www.codeproject.com/Articles/42884/Implementation-of-Auto-Logoff-Based-on-User-Inacti
but this doesn’t port to Avalonia. It involves the following code which goes in the code-behind of the MainWindow:
private void InitializeAutoLogoffFeature()
{
HwndSource windowSpecificOSMessageListener = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
windowSpecificOSMessageListener.AddHook(new HwndSourceHook(CallBackMethod));
AutoLogOff.LogOffTime = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["LogOffIdleMinutes"]);
AutoLogOff.MakeAutoLogOffEvent += new AutoLogOff.MakeAutoLogOff(AutoLogOff_MakeAutoLogOffEvent);
AutoLogOff.StartAutoLogoffOption();
string time = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
//tblStatus.Text = "Timer is started at " + ": " + time;
}
private IntPtr CallBackMethod(IntPtr hwnd, int msg, IntPtr wParam, 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)
{
AutoLogOff.ResetLogoffTimer();
}
else
{
System.Diagnostics.Debug.WriteLine(msg.ToString());
}
return IntPtr.Zero;
}
The stuff in the “AutoLogOff” class looks easy to reproduce. The parts that I don’t know how to reproduce are mainly just the following two lines and the IntPtr CallBackMethod:
HwndSource windowSpecificOSMessageListener = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
windowSpecificOSMessageListener.AddHook(new HwndSourceHook(CallBackMethod));
// Listening OS message to test whether it is a user activity
if ((msg >= 0x0200 && msg <= 0x020A) || (msg <= 0x0106 && msg >= 0x00A0) || msg == 0x0021)
{
AutoLogOff.ResetLogoffTimer();
}
Right now my app is just intended to target Windows Desktop, however if there’s a general way of doing it so it works in WebAssembly, MAUI and MacOS that’d be great.
Thanks!