65.9K
CodeProject is changing. Read more.
Home

Window force forward

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.93/5 (7 votes)

Jun 9, 2006

CPOL

1 min read

viewsIcon

29211

downloadIcon

242

A small example of how a program window can be brought up when the user input may need it.

Sample Image - ForceForward.jpg

Introduction

After all those times that I have used code examples and code snippets from The Code Project, it is time to contribute something back. This article shows how easy it is to use two pre-programmed properties in the Form class in your own project. It shows how easily the this.WindowState and this.TopMost can be used.

The Code

The force forward function is small and simple, it is called with a bool value that forces the window to be on top, or resets it back to normal. If the window has been minimized to the taskbar, the window state is changed to normal so it will pop up from the taskbar.

private void ForceForward(bool forceForward)
{
    if (forceForward)
    {
        // Force the window up from taskbar if needed...
        if (this.WindowState == FormWindowState.Minimized)
            this.WindowState = FormWindowState.Normal;

        // Top most windows...
        this.TopMost = true;
    }

    // If not force forward, set TopMost back
    // to original state...
    else
        this.TopMost = false;
}

The Sequence

This program uses a timer to demonstrate. The delay is set to five seconds as the timer is started. For each time the timer “ticks”, the delay decreases by one. When the delay has reached down to zero (or somehow below), it executes ForceForward(true) and then ends the sequence.

private void btStart_Click(object sender, EventArgs e)
{
    // Start button set to false!
    btStart.Enabled = false;

    // Run once every second (1000ms = 1sec)...
    timer.Enabled = true;
    timer.Interval = 1000;

    // Delay is set to 5 seconds...
    delay = 5;

    // Show on form in begining of countdown...
    lbCountdown.Text = delay.ToString();
    this.Text = delay.ToString();

    // Start the timer...
    timer.Start();
}

private void timer_Tick(object sender, EventArgs e)
{
    // Decrease delay...
    delay--;

    // Show countdown status...
    lbCountdown.Text = delay.ToString();
    this.Text = delay.ToString();

    // When delay has reached zero, ForceForward...
    if (delay <= 0)
    {
        ForceForward(true);
        EndSequence();
    }
}

private void EndSequence()
{
    // Stop and disable...
    timer.Stop();
    timer.Enabled = false;

    // Reset countdown label...
    lbCountdown.Text = "";
    this.Text = "Force Forward";

    // Start button now enabled for next force...
    btStart.Enabled = true;

    // Now set back to normal... 
    ForceForward(false);
}

When the end sequence has been executed, the timer is stopped and the program turns back to normal; it does not “top most” windows any more.