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.
Asked
Active
Viewed 37 times
0
-
But should you be determining what window appears to the user in their multitasking environment? – Charles May Jul 13 '17 at 17:41
-
this is a overlay application that has a check box to activate this feature. – Jacob Lenertz Jul 13 '17 at 17:42
-
What if someone else wrote the same program? – LarsTech Jul 13 '17 at 18:23
-
Just in case you are using WPF, it has a built-in feature to keep the application on top. – Ian H. Jul 13 '17 at 18:25
2 Answers
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:

NetMage
- 26,163
- 3
- 34
- 55