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

8

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

我认为我可以让我的控制台应用程序从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。
2个回答

14

你可以从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();
    }
}

0

谢谢Kieren。我如何使用Windows表单创建控制台窗口? - Santhosh
我认为他的意思是,不要写控制台应用程序,而是写一个Windows窗体应用程序。 - Just a HK developer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接