【问题标题】:How to set a console application window to be the top most window (C#)?如何将控制台应用程序窗口设置为最顶层窗口(C#)?
【发布时间】:2011-03-23 03:36:12
【问题描述】:

如何将控制台应用程序设置为最顶部的窗口。我正在.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。

【问题讨论】:

    标签: c# window console-application


    【解决方案1】:

    您可以通过 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();
        }
    }
    

    【讨论】:

      【解决方案2】:

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

      但是这有点老套,建议使用 Windows 窗体或 WPF 创建您自己的控制台窗口。

      【讨论】:

      • 谢谢基伦。如何使用 Windows 窗体创建控制台窗口?
      • 我认为他想说的是,与其编写控制台应用程序,不如编写一个 Windows 窗体应用程序。
      猜你喜欢
      • 2018-10-06
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 2019-01-18
      相关资源
      最近更新 更多