如何将控制台应用程序窗口设置为最顶层的窗口(C#)?

如何将控制台应用程序设置为最顶层的窗口。 我正在使用.NET构建控制台应用程序(我正在使用C#,甚至可以对非托管代码进行pinvokes)。

我以为我可以让我的控制台应用程序派生自Form类

class MyConsoleApp : Form { public MyConsoleApp() { this.TopLevel = true; this.TopMost = true; this.CenterToScreen(); } public void DoSomething() { //.... } public static void Main() { MyConsoleApp consoleApp = new MyConsoleApp(); consoleApp.DoSomething(); } } 

但是这不起作用。 我不确定Windows窗体上设置的属性是否适用于控制台UI。

您可以从Windows API P / Invoke SetWindowPos

 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(); } } 

您可以使用FindWindow with P / Invoke( http://msdn.microsoft.com/en-us/library/ms633499 ( VS.85 ) .aspx )然后以某种方式设置扩展样式以使用WS_EX_TOPMOST – 请参阅P / Invoke中的SetWindowLonghttp://www.pinvoke.net/default.aspx/coredll/SetWindowLong.html )。

然而,它有点hacky并建议使用Windows窗体或WPF创建自己的控制台窗口。