Click here to Skip to main content
15,892,298 members
Articles / Programming Languages / C#

How to check for user inactivity with and without platform invokes in C#

Rate me:
Please Sign up or sign in to vote.
4.87/5 (67 votes)
22 Dec 200414 min read 299.9K   7.4K   179  
Within the last month, two fellow programmers asked how to implement a timeout after a certain interval of inactivity. This article features four and a half ways of doing this.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;
using UserInactivityMonitoring;

namespace TestApplication
{
	public class MainForm : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button CreateCtrlMonButton;
		private System.ComponentModel.Container components = null;
		private System.Windows.Forms.TextBox OutputTextBox;
		private System.Windows.Forms.Button DisposeMonButton;
		private System.Windows.Forms.Button NullMonVarButton;
		private System.Windows.Forms.Button EnableMonButton;
		private System.Windows.Forms.Button DisableMonButton;
		private System.Windows.Forms.Button TriggerCGButton;
		private System.Windows.Forms.GroupBox CreateOptsGroup;
		private System.Windows.Forms.ComboBox MonTypeComboBox;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.TextBox IntervalTextBox;
		private System.Windows.Forms.CheckBox SyncCheckBox;
		private System.Windows.Forms.CheckBox MonKeyboardCheckBox;
		private System.Windows.Forms.CheckBox MonMouseCheckBox;
		private System.Windows.Forms.Button ShowMsgBoxButton;
		private System.Windows.Forms.Button ShowOtherWindowButton;
		private System.Windows.Forms.CheckBox ModalWndCheckBox;

		private IInactivityMonitor inactivityMonitor = null;

		public MainForm()
		{
			InitializeComponent();
		}

		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Vom Windows Form-Designer generierter Code
		private void InitializeComponent()
		{
			this.CreateCtrlMonButton = new System.Windows.Forms.Button();
			this.OutputTextBox = new System.Windows.Forms.TextBox();
			this.DisposeMonButton = new System.Windows.Forms.Button();
			this.NullMonVarButton = new System.Windows.Forms.Button();
			this.EnableMonButton = new System.Windows.Forms.Button();
			this.DisableMonButton = new System.Windows.Forms.Button();
			this.TriggerCGButton = new System.Windows.Forms.Button();
			this.CreateOptsGroup = new System.Windows.Forms.GroupBox();
			this.MonMouseCheckBox = new System.Windows.Forms.CheckBox();
			this.MonKeyboardCheckBox = new System.Windows.Forms.CheckBox();
			this.SyncCheckBox = new System.Windows.Forms.CheckBox();
			this.MonTypeComboBox = new System.Windows.Forms.ComboBox();
			this.label1 = new System.Windows.Forms.Label();
			this.IntervalTextBox = new System.Windows.Forms.TextBox();
			this.ShowMsgBoxButton = new System.Windows.Forms.Button();
			this.ShowOtherWindowButton = new System.Windows.Forms.Button();
			this.ModalWndCheckBox = new System.Windows.Forms.CheckBox();
			this.CreateOptsGroup.SuspendLayout();
			this.SuspendLayout();
			// 
			// CreateCtrlMonButton
			// 
			this.CreateCtrlMonButton.Location = new System.Drawing.Point(8, 8);
			this.CreateCtrlMonButton.Name = "CreateCtrlMonButton";
			this.CreateCtrlMonButton.Size = new System.Drawing.Size(160, 24);
			this.CreateCtrlMonButton.TabIndex = 0;
			this.CreateCtrlMonButton.Text = "Create Monitor";
			this.CreateCtrlMonButton.Click += new System.EventHandler(this.CreateCtrlMonButton_Click);
			// 
			// OutputTextBox
			// 
			this.OutputTextBox.Location = new System.Drawing.Point(8, 280);
			this.OutputTextBox.Multiline = true;
			this.OutputTextBox.Name = "OutputTextBox";
			this.OutputTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
			this.OutputTextBox.Size = new System.Drawing.Size(512, 280);
			this.OutputTextBox.TabIndex = 10;
			this.OutputTextBox.Text = "";
			// 
			// DisposeMonButton
			// 
			this.DisposeMonButton.Location = new System.Drawing.Point(184, 8);
			this.DisposeMonButton.Name = "DisposeMonButton";
			this.DisposeMonButton.Size = new System.Drawing.Size(160, 24);
			this.DisposeMonButton.TabIndex = 1;
			this.DisposeMonButton.Text = "Dispose Monitor Object";
			this.DisposeMonButton.Click += new System.EventHandler(this.DisposeMonButton_Click);
			// 
			// NullMonVarButton
			// 
			this.NullMonVarButton.Location = new System.Drawing.Point(360, 8);
			this.NullMonVarButton.Name = "NullMonVarButton";
			this.NullMonVarButton.Size = new System.Drawing.Size(160, 24);
			this.NullMonVarButton.TabIndex = 2;
			this.NullMonVarButton.Text = "Null Monitor Variable";
			this.NullMonVarButton.Click += new System.EventHandler(this.NullMonVarButton_Click);
			// 
			// EnableMonButton
			// 
			this.EnableMonButton.Location = new System.Drawing.Point(8, 40);
			this.EnableMonButton.Name = "EnableMonButton";
			this.EnableMonButton.Size = new System.Drawing.Size(160, 24);
			this.EnableMonButton.TabIndex = 3;
			this.EnableMonButton.Text = "Enable Monitor";
			this.EnableMonButton.Click += new System.EventHandler(this.EnableMonButton_Click);
			// 
			// DisableMonButton
			// 
			this.DisableMonButton.Location = new System.Drawing.Point(184, 40);
			this.DisableMonButton.Name = "DisableMonButton";
			this.DisableMonButton.Size = new System.Drawing.Size(160, 24);
			this.DisableMonButton.TabIndex = 4;
			this.DisableMonButton.Text = "Disable Monitor";
			this.DisableMonButton.Click += new System.EventHandler(this.DisableMonButton_Click);
			// 
			// TriggerCGButton
			// 
			this.TriggerCGButton.Location = new System.Drawing.Point(360, 40);
			this.TriggerCGButton.Name = "TriggerCGButton";
			this.TriggerCGButton.Size = new System.Drawing.Size(160, 24);
			this.TriggerCGButton.TabIndex = 5;
			this.TriggerCGButton.Text = "Collect Garbage";
			this.TriggerCGButton.Click += new System.EventHandler(this.TriggerCGButton_Click);
			// 
			// CreateOptsGroup
			// 
			this.CreateOptsGroup.Controls.Add(this.MonMouseCheckBox);
			this.CreateOptsGroup.Controls.Add(this.MonKeyboardCheckBox);
			this.CreateOptsGroup.Controls.Add(this.SyncCheckBox);
			this.CreateOptsGroup.Controls.Add(this.MonTypeComboBox);
			this.CreateOptsGroup.Controls.Add(this.label1);
			this.CreateOptsGroup.Controls.Add(this.IntervalTextBox);
			this.CreateOptsGroup.Location = new System.Drawing.Point(8, 160);
			this.CreateOptsGroup.Name = "CreateOptsGroup";
			this.CreateOptsGroup.Size = new System.Drawing.Size(512, 100);
			this.CreateOptsGroup.TabIndex = 9;
			this.CreateOptsGroup.TabStop = false;
			this.CreateOptsGroup.Text = "Creation Options";
			// 
			// MonMouseCheckBox
			// 
			this.MonMouseCheckBox.Location = new System.Drawing.Point(360, 64);
			this.MonMouseCheckBox.Name = "MonMouseCheckBox";
			this.MonMouseCheckBox.TabIndex = 5;
			this.MonMouseCheckBox.Text = "Monitor Mouse";
			// 
			// MonKeyboardCheckBox
			// 
			this.MonKeyboardCheckBox.Location = new System.Drawing.Point(176, 64);
			this.MonKeyboardCheckBox.Name = "MonKeyboardCheckBox";
			this.MonKeyboardCheckBox.Size = new System.Drawing.Size(120, 24);
			this.MonKeyboardCheckBox.TabIndex = 4;
			this.MonKeyboardCheckBox.Text = "Monitor Keyboard";
			// 
			// SyncCheckBox
			// 
			this.SyncCheckBox.Location = new System.Drawing.Point(16, 64);
			this.SyncCheckBox.Name = "SyncCheckBox";
			this.SyncCheckBox.Size = new System.Drawing.Size(128, 24);
			this.SyncCheckBox.TabIndex = 3;
			this.SyncCheckBox.Text = "Synchronize Events";
			// 
			// MonTypeComboBox
			// 
			this.MonTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
			this.MonTypeComboBox.Location = new System.Drawing.Point(16, 24);
			this.MonTypeComboBox.Name = "MonTypeComboBox";
			this.MonTypeComboBox.Size = new System.Drawing.Size(168, 21);
			this.MonTypeComboBox.TabIndex = 0;
			// 
			// label1
			// 
			this.label1.AutoSize = true;
			this.label1.Location = new System.Drawing.Point(248, 24);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(118, 16);
			this.label1.TabIndex = 1;
			this.label1.Text = "Interval in milliseconds";
			// 
			// IntervalTextBox
			// 
			this.IntervalTextBox.Location = new System.Drawing.Point(368, 24);
			this.IntervalTextBox.Name = "IntervalTextBox";
			this.IntervalTextBox.TabIndex = 2;
			this.IntervalTextBox.Text = "1000";
			// 
			// ShowMsgBoxButton
			// 
			this.ShowMsgBoxButton.Location = new System.Drawing.Point(184, 88);
			this.ShowMsgBoxButton.Name = "ShowMsgBoxButton";
			this.ShowMsgBoxButton.Size = new System.Drawing.Size(160, 24);
			this.ShowMsgBoxButton.TabIndex = 7;
			this.ShowMsgBoxButton.Text = "Show Message Box";
			this.ShowMsgBoxButton.Click += new System.EventHandler(this.ShowMsgBoxButton_Click);
			// 
			// ShowOtherWindowButton
			// 
			this.ShowOtherWindowButton.Location = new System.Drawing.Point(8, 88);
			this.ShowOtherWindowButton.Name = "ShowOtherWindowButton";
			this.ShowOtherWindowButton.Size = new System.Drawing.Size(160, 24);
			this.ShowOtherWindowButton.TabIndex = 6;
			this.ShowOtherWindowButton.Text = "Show Some Other Window";
			this.ShowOtherWindowButton.Click += new System.EventHandler(this.ShowOtherWindowButton_Click);
			// 
			// ModalWndCheckBox
			// 
			this.ModalWndCheckBox.Location = new System.Drawing.Point(8, 120);
			this.ModalWndCheckBox.Name = "ModalWndCheckBox";
			this.ModalWndCheckBox.Size = new System.Drawing.Size(136, 24);
			this.ModalWndCheckBox.TabIndex = 8;
			this.ModalWndCheckBox.Text = "Show modal Window";
			// 
			// MainForm
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(530, 567);
			this.Controls.Add(this.ModalWndCheckBox);
			this.Controls.Add(this.ShowOtherWindowButton);
			this.Controls.Add(this.ShowMsgBoxButton);
			this.Controls.Add(this.CreateOptsGroup);
			this.Controls.Add(this.TriggerCGButton);
			this.Controls.Add(this.DisableMonButton);
			this.Controls.Add(this.EnableMonButton);
			this.Controls.Add(this.NullMonVarButton);
			this.Controls.Add(this.DisposeMonButton);
			this.Controls.Add(this.OutputTextBox);
			this.Controls.Add(this.CreateCtrlMonButton);
			this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
			this.MaximizeBox = false;
			this.Name = "MainForm";
			this.Text = "Inactivity Monitor Test Application";
			this.Load += new System.EventHandler(this.MainForm_Load);
			this.CreateOptsGroup.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion

		[STAThread]
		static void Main() 
		{
			try
			{
				Application.Run(new MainForm());
			}
			catch (Exception e)
			{
				MessageBox.Show(e.Message);
			}
		}

		private void TimeElapsed(object sender, ElapsedEventArgs e)
		{
			try
			{
				if (this.InvokeRequired)
					WriteOutput("Event 'Elapsed' occured (Invoke() would have been required)");
				else
					WriteOutput("Event 'Elapsed' occured (synchronized call)");
			}
			catch (Exception exception)
			{
				WriteOutput("Exception occured: " + exception.Message);
			}
		}

		private void Reactivated(object sender, EventArgs e)
		{
			try
			{
				if (this.InvokeRequired)
					WriteOutput("Event 'Reactivated' occured (Invoke() would have been required)");
				else
					WriteOutput("Event 'Reactivated' occured (synchronized call)");
			}
			catch (Exception exception)
			{
				WriteOutput("Exception occured: " + exception.Message);
			}
		}

		private void CreateCtrlMonButton_Click(object sender, System.EventArgs e)
		{
			try
			{
				switch (MonTypeComboBox.SelectedIndex)
				{
					case 0:
						inactivityMonitor = MonitorCreator.CreateInstance(this, MonitorType.ControlMonitor);
						WriteOutput("New 'ControlMonitor' created");
						break;
					case 1:
						inactivityMonitor = MonitorCreator.CreateInstance(MonitorType.ApplicationMonitor);
						WriteOutput("New 'ApplicationMonitor' created");
						break;
					case 2:
						inactivityMonitor = MonitorCreator.CreateInstance(MonitorType.LastInputMonitor);
						WriteOutput("New 'LastInputMonitor' created");
						break;
					case 3:
						inactivityMonitor = MonitorCreator.CreateInstance(MonitorType.ThreadHookMonitor);
						WriteOutput("New local 'HookMonitor' created");
						break;
					case 4:
						inactivityMonitor = MonitorCreator.CreateInstance(MonitorType.GlobalHookMonitor);
						WriteOutput("New global 'HookMonitor' created");
						break;
					default:
						WriteOutput("Unknown monitor type (" + MonTypeComboBox.SelectedText + ")");
						return;
				}
				if (SyncCheckBox.Checked)
					inactivityMonitor.SynchronizingObject = this;
				if (!MonKeyboardCheckBox.Checked)
					inactivityMonitor.MonitorKeyboardEvents = false;
				if (!MonMouseCheckBox.Checked)
					inactivityMonitor.MonitorMouseEvents = false;
				inactivityMonitor.Interval = Convert.ToDouble(IntervalTextBox.Text);
				inactivityMonitor.Elapsed += new ElapsedEventHandler(TimeElapsed);
				inactivityMonitor.Reactivated += new EventHandler(Reactivated);
			}
			catch (Exception exception)
			{
				WriteOutput("Exception occured: " + exception.Message);
			}
		}

		private void WriteOutput(string output)
		{
			OutputTextBox.Text += output + "\r\n";
			OutputTextBox.SelectionStart = OutputTextBox.Text.Length;
			OutputTextBox.ScrollToCaret();
		}

		private void DisposeMonButton_Click(object sender, System.EventArgs e)
		{
			try
			{
				inactivityMonitor.Dispose();
				WriteOutput("Monitor object disposed");
			}
			catch (Exception exception)
			{
				WriteOutput("Exception occured: " + exception.Message);
			}
		}

		private void NullMonVarButton_Click(object sender, System.EventArgs e)
		{
			try
			{
				inactivityMonitor = null;
				WriteOutput("Set monitor object variable to null");
			}
			catch (Exception exception)
			{
				WriteOutput("Exception occured: " + exception.Message);
			}
		}

		private void MainForm_Load(object sender, System.EventArgs e)
		{
			MonTypeComboBox.Items.Add(typeof(ControlMonitor).Name);
			MonTypeComboBox.Items.Add(typeof(ApplicationMonitor).Name);
			MonTypeComboBox.Items.Add(typeof(LastInputMonitor).Name);
			MonTypeComboBox.Items.Add(typeof(HookMonitor).Name + " (local)");
			MonTypeComboBox.Items.Add(typeof(HookMonitor).Name + " (global)");
			MonTypeComboBox.SelectedIndex = 0;
		}

		private void EnableMonButton_Click(object sender, System.EventArgs e)
		{
			try
			{
				inactivityMonitor.Enabled = true;
				WriteOutput("Monitor enabled");
			}
			catch (Exception exception)
			{
				WriteOutput("Exception occured: " + exception.Message);
			}
		}

		private void DisableMonButton_Click(object sender, System.EventArgs e)
		{
			try
			{
				inactivityMonitor.Enabled = false;
				WriteOutput("Monitor disabled");
			}
			catch (Exception exception)
			{
				WriteOutput("Exception occured: " + exception.Message);
			}
		}

		private void TriggerCGButton_Click(object sender, System.EventArgs e)
		{
			try
			{
				GC.Collect();
				WriteOutput("Collected garbage");
			}
			catch (Exception exception)
			{
				WriteOutput("Exception occured: " + exception.Message);
			}		
		}

		private void ShowMsgBoxButton_Click(object sender, System.EventArgs e)
		{
			MessageBox.Show("fhqwhgads");
		}

		private void ShowOtherWindowButton_Click(object sender, System.EventArgs e)
		{
			if (ModalWndCheckBox.Checked)
				new SomeOtherForm().ShowDialog(this);
			else
				new SomeOtherForm().Show();
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions