Make Form Stay Always on Top of Every Window

Introduction 

Some time we require that application window should always stay on top like when we making download manager like thing we need to show progress of download even if our main application form is minimized in this case we need to show a small window form that will be always on top of every other application.

Language

C Sharp .net 2.0/3.5

Implementation

1.gif

Now to implement this functionality we need to call some win32 Functions that are available in user32.dll that is SetWindowPos() that will position our window's Z order so that our window will be always on top .

So to call user32.dll's function we need to Import namespace 

using System.Runtime.InteropServices;

First of all we need some constants that will be used In function in global portion of our form

static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;
const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

and one function's prototype like below 

[DllImport("user32.dll")] 
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

In on Load Event of Form Call that function like below

SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

Now when we run our application our form will be top of every application..

Complete Source Code

namespace WindowsFormsApplication52

{

    public partial class Form1 : Form

    {

        static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);

        static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);

        static readonly IntPtr HWND_TOP = new IntPtr(0);

        static readonly IntPtr HWND_BOTTOM = new IntPtr(1);

        const UInt32 SWP_NOSIZE = 0x0001;

        const UInt32 SWP_NOMOVE = 0x0002;

        const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

 

        [DllImport("user32.dll")]

        [return: MarshalAs(UnmanagedType.Bool)]

        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

        }

    }

}


Similar Articles