Monday, May 31, 2010

Query Currently Active Form

In my applications I sometimes want to know, whether a specific form has the focus in the moment, meaning it is active at this time. Or, for applications with only one form, whether the whole application has the focus.
With this the current form is adressed. The property Focused checks, whether the form has focus.
The following little sample code can for example be copied in the Tick event of a timer and switches periodically the background color of the form, depending whether the form is active or not:
private void timer1_Tick(object sender, EventArgs e)
{
    if (this.Focused)
        this.BackColor = Color.Red; // red if form has focus
    else
        this.BackColor = Color.Green; // green otherwise
}

No comments:

Post a Comment