0

I want to be able to have my application to always be on top. so when I open a new program and that becomes on top even though I have this.TopLevel value set to true, the application will see it is not on top no more and then go back on top. I know I can do this with a timer, but I am hoping their is a better way.

Jacob Lenertz
  • 81
  • 1
  • 13

2 Answers2

3

You can use a method located in user32.dll.

using System.Runtime.InteropServices;

You are going to need these variables:

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

Import the method from the DLL...

[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);

Then in your code, use this to set the window position to the topmost window.

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

I hope this helps you!

Ian H.
  • 3,840
  • 4
  • 30
  • 60
1

I suggest you catch the event for new windows and see if you are on top after the new window opens:

https://stackoverflow.com/a/40698254/2557128

NetMage
  • 26,163
  • 3
  • 34
  • 55