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

如何将控制台应用程序窗口设置为最顶部的窗口(C#)?,c#,window,console-application,C#,Window,Console Application,如何将控制台应用程序设置为最上面的窗口。我正在.NET中构建控制台应用程序(我正在使用C#,甚至对非托管代码使用pinvokes也可以) 我想我的控制台应用程序可以从表单类派生 class MyConsoleApp : Form { public MyConsoleApp() { this.TopLevel = true; this.TopMost = true; this.CenterToScreen(); } publ

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

我想我的控制台应用程序可以从表单类派生

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。

您可以将
FindWindow
与p/Invoke()一起使用,然后以某种方式将扩展样式设置为使用
WS\u EX\u top
-请参见p/Invoke()中的
SetWindowLong


不过,这有点不太成熟,建议您使用Windows窗体或WPF创建自己的控制台窗口。

您可以从Windows API调用
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();
    }
}

谢谢你,基伦。如何使用Windows窗体创建控制台窗口?我想他是想说,与其编写控制台应用程序,不如编写Windows窗体应用程序。