Search code examples
c#visual-studiotoplevel

Create an Event for when this,toplevel value changes


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.


Solution

  • 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!