Tue 27 Jan 2009

Today I was required to implement detecting the idle time or user inactivity in windows form. Here it is how it works
The theme behind is the usage of MessageFiler that will be intercepting calls (Keyboard / Mouse activities) and usage of System.Windows.Forms.Timer

Step 1.

Create MessageFilter class as

using System;
using System.Windows.Forms;

 public class MessageFilter : IMessageFilter
    {
       //Following are the Windows API hex values. You can find more at http://faisal.azmza.com/post/2009/01/Values-of-Windows-API.aspx
       // Here we are only interested in only Keyboard and Mouse activities
        private int WM_LBUTTONDOWN = 0x0201;
        private int WM_KEYDOWN = 0x0100;
        private int WM_RBUTTONDOWN = 0x0204;
        private int WM_MBUTTONDOWN = 0x0207;
        private int WM_MOUSEWHEEL = 0x020A;
        private int WM_MOUSEMOVE = 0x0200;

        public bool PreFilterMessage(ref Message m)
        {
            if (m.Msg == WM_MOUSEMOVE || m.Msg == WM_KEYDOWN || m.Msg == WM_LBUTTONDOWN || m.Msg == WM_MOUSEWHEEL || m.Msg == WM_RBUTTONDOWN || m.Msg == WM_MBUTTONDOWN)
            {
                //Reset the timer of form1
                Form1.timerIdle.Stop();
                Form1.timerIdle.Start();
            }
            return false;
        }
    }

Step 2:

In the form where you actually want to implement what to do if user is inactive for particular period, like redirecting to Login page, performing Session / objects cleanup, hiding or locking touchy form etc etc, put following peace of code,

a) Declare static timer as

//Reason for taking this timer as static becasue we need to reset timer in MessageFilter class.
//If don't want to use static then you can implement your own logic. The theme is to reset the timer in MessageFilter on any Keyboard or Mouse activity

internal static Timer timerIdle;

b) Put following initializing code after InitializeComponent or on Form_Load. Note to set Interval of timer to your requirement. Here it is set for 5 minutes.

            timerIdle = new System.Windows.Forms.Timer();
            timerIdle.Enabled = true;
            timerIdle.Interval = 50000; // Idle time period. Here after 5 minutes perform task in  timerIdle_Tick
            timerIdle.Tick += new EventHandler(timerIdle_Tick);

 c) Put following inside your form

        private void timerIdle_Tick(object sender, EventArgs e)
        {
            //Here perform your action by first validating that idle task is not already running.
           // If you want to redirect user to login page, then first check weather login page is already displayed or not
           // if not then show loign page. Same logic for other task or Implement your own.
           // Remember after every five minutes or period you defined above this timerIdle_Tick will be called
           //so first check weather idle task is already running or not. If not then perform
            //if (Login.Visible == false)
            //{
                   //PerformNecessoryActions();
                  //ShowLoginForm();
            //}
        }

 

Step 3.

So far we have created MessageFilter class (On keyboard or mouse activity it will reset the timer of form). In form we have declared and initialize timer. On timer_Tick event we have implement the task which we need to do when user become inactive for particular period of time. Now in last step, Add our MessageFilter class in Application to intercept calls as

static void Main(string[] args)
{
            Application.AddMessageFilter(new MessageFilter());
            Application.Run(new Form1());
}


Hope it helps.

 

Comments (1)
Fri 23 Jan 2009

In first sight you will not see  PasswordChar property in ToolStripTextBox.
If you want Password char in ToolStripTextBox and To allow ToolStripTextBox to act as Password textbox like * do following

ToolStripTextBox1.TextBox.PasswordChar = '*';


===========================


Usually ToolStripTextBox.Focus() doesn't focus to ToolStripTextBox when opening form or on form load.
To set focus on ToolStripTextBox when opening form or form load, do following

In FOrm1_Activated event

        private void Form1_Activated(object sender, EventArgs e)
        {
            ToolStripTextBox1.Focus();
        }

Or

on Form1_Load event

this.ActiveControl = ToolStripTextBox1.Control;

 

Tags: ,
Comments here
Wed 21 Jan 2009

In windows form, if you don't want user to close the form by pressing Alt+F4 or Cross (x) button accidently and without saving existing form status, you may need to capture the form close event.

In the FormClosing event of form, FormClosingEventArg has a property called CloseReason. This is very usefull because if you want the Form to stop closing if the closing reason was CloseReason.UserClosing or some thing else.

You can do e.Cancel = true to prevent form being closed, then do something in your code and finally close the form programatically.

e.g.


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
                e.Cancel = true;

                //Check the status of form, Save form status if required or other logic

                this.Close();
        }

 

 

Tags: ,
Comments here
Wed 21 Jan 2009

In windows form, if you have richtextbox or multiline textbox then usually enter key use to enter a new line.

But if AcceptButton property of Form is set for some action/button press, then pressing enter key in richtextbox or multiline textbox doesn't enter a new line rather AcceptButton calls.

To supress this set the property AcceptsTab to true in richtexbox. In case of multiline textbox / control set AcceptsReturn and AcceptTab property to true.

 

Tags: ,
Comments (3)
Wed 21 Jan 2009

Tonight in windows form, using C# language I required to use key combination like we use Ctrl+S to save form, CTRL+F to find etc.

In windows form, its quite easy. Just enable KeyPreview property to true. This property makes the form get the key events before the controls, so you can set the KeyPress event on the form.

Form1.KeyPreview = true;

After that, set the form event for the keypress/key down

this.KeyDown += new KeyEventHandler(this.Form1_KeyDown);

Now shortcut part comes here, follow like this

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
 if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.S)
 {  
  //SaveData();
 }
 else if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.F)
 {  
  //Find();
 }
}

Hope it helps some one.

 

Tags: ,
Comments (1)
Thu 1 Jan 2009

Today I need to convert between string and hexadecimal in C#...

         public string StrToHex(string plainText)
        {
            char[] charArray = plainText.ToCharArray();

            StringBuilder sb = new StringBuilder();
            int num;
            string hex;
            for (int i = 0; i < charArray.Length; i++)

            {
                if (i > 0)
                {
                    sb.Append("-");
                }
                num = Convert.ToInt32(charArray[i]);

                hex = num.ToString("x");
                sb.Append(hex);
            }

             return sb.ToString();
        }

 ===========

         public string HexToStr(string hexaText)
        {
           string[] strArray = hexaText.Split(new char[] { '-' });
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < strArray.Length; ++i)
            {
                sb.Append((char)Convert.ToInt32(strArray[i], 16));
            }
            return sb.ToString();
        }

 ============ 

Implementation as

string str = "TestString";
string hexStr = StrToHex(str);   // => 54-65-73-74-53-74-72-69-6e-67
str = HexToStr(hexStr); // => TestString

 

  

Tags: ,
Comments here
Sat 13 Sep 2008

A quick overview!...

NET framework 2.0:

It brings a lot of evolution in class of the framework and refactor control including the support of

Generics
Anonymous methods
Partial class
Nullable type
The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more
Full 64-bit support for both the x64 and the IA64 hardware platforms
New personalization features for ASP.NET, such as support for themes, skins and webparts.
.NET Micro Framework


.NET framework 3.0:

Also called WinFX,includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems and provides

Windows Communication Foundation (WCF), formerly called Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
Windows Presentation Foundation (WPF), formerly called Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies.
Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
Windows CardSpace, formerly called InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website


.NET framework 3.5:

It implement Linq evolution in language. So we have the folowing evolution in class:

Linq for SQL, XML, Dataset, Object
Addin system
p2p base class
Active directory
ASP.NET Ajax
Anonymous types with static type inference
Paging support for ADO.NET
ADO.NET synchronization API to synchronize local caches and server side datastores
Asynchronous network I/O API
Support for HTTP pipelining and syndication feeds.
New System.CodeDom namespace.

 

Comments (4)




Ads