Tuesday, May 29, 2012

Bring Application to the Front

In this post I want to show, how to bring an application to the front using C#. The presented method should work, no matter if the program currently has the focus or is minimized, granting the application the input focus and set it as the top most window on the screen.
By default in C# forms have the property TopMost and the function BringToFront(), but these just move the form forward in relation to other forms of the application. Therefore, we have to dig a bit deeper and to use the Win32 API.

For above needs we need the function SetForegroundWindow(), which expects the handle of the target window. It grants the application the input focus, if the application is minimized though, it is now shown. The reason is, that minimized applications do not have a window which could be shown.

To create this window we use the function ShowWindowAsync(). It expects 2 arguments, the first one is again the window handle, the second one an integer value determining how the window is shown. For an overview over all possibilities I want to refer to the MSDN, I only use SW_RESTORE, which shows the window in its original size.

We now simply add a request asking whether the window is minimized, which is possible via the function IsIconic().

The following program uses the previously described functions to bring the program after elapse of the timer event to the front:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        private static extern
            bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern
            bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        private static extern
            bool IsIconic(IntPtr hWnd);

        private const int SW_RESTORE = 9;

        public Form1()
        {
            InitializeComponent();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (IsIconic(this.Handle))
                ShowWindowAsync(this.Handle, SW_RESTORE);

            SetForegroundWindow(this.Handle);
        }
    }
}

No comments:

Post a Comment