Jul 27, 2012

How to display any Application on top of other Windows using C#

1 comment
Normally in dot net we have seen by setting property Form.TopMost = true, we can display that particular form on top of other.

But how to achieve same thing for any non-form application? For example to display notepad on top of other window?

We can do this using SetWindowPos Win32 API function. Let's see the step by step procedure,

1. Define SetWindowPos Win32 API function.

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int cx, int cy, int uFlags);

2. Load all the processes those are running.

private void btnLoadProcesses_Click(object sender, EventArgs e)
   //Getting all the process
   Process[] processes = Process.GetProcesses();
   cboProcesses.DisplayMember = "MainWindowTitle";
   cboProcesses.ValueMember = "MainWindowHandle";
   foreach (Process process in processes)
      //Adding only process which has got Window Title.
      if (process.MainWindowTitle.Length >= 1)

3. Show the selected application(process) on top of other windows.
private void cboProcesses_SelectedIndexChanged(object sender, EventArgs e)
    Process process = cboProcesses.SelectedItem as Process;
    SetWindowPos(process.MainWindowHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);


If you feel this is helpful or you like it, Please share this using share buttons available on page.

1 comment :