How to set a console application window to be the top most window (C#)?

前端 未结 2 380
谎友^
谎友^ 2020-12-25 08:48

How do i set a console application to be the top most window. I am building the console application in .NET (i am using C# and maybe even pinvokes to unmanaged code is ok).<

相关标签:
2条回答
  • 2020-12-25 09:29

    You can P/Invoke SetWindowPos from the Windows API:

    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;
    
    class Program
    {
        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool SetWindowPos(
            IntPtr hWnd, 
            IntPtr hWndInsertAfter, 
            int x, 
            int y, 
            int cx, 
            int cy, 
            int uFlags);
    
        private const int HWND_TOPMOST = -1;
        private const int SWP_NOMOVE = 0x0002;
        private const int SWP_NOSIZE = 0x0001;
    
        static void Main(string[] args)
        {
            IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;
    
            SetWindowPos(hWnd, 
                new IntPtr(HWND_TOPMOST), 
                0, 0, 0, 0, 
                SWP_NOMOVE | SWP_NOSIZE);
    
            Console.ReadKey();
        }
    }
    
    0 讨论(0)
  • 2020-12-25 09:41

    You could use FindWindow with P/Invoke (http://msdn.microsoft.com/en-us/library/ms633499(VS.85).aspx) then somehow set the extended style to use WS_EX_TOPMOST - see SetWindowLong at P/Invoke (http://www.pinvoke.net/default.aspx/coredll/SetWindowLong.html ).

    However it's all a bit hacky and would recommend creating your own console window using Windows Forms or WPF.

    0 讨论(0)
提交回复
热议问题