最大化控制台窗口 - C#

22

我正在使用C#编写控制台应用程序,需要将控制台最大化。但当我点击控制台窗口的最大化按钮时,它只会在高度上最大化而不是宽度上。我尝试使用以下代码:

   Console.WindowWidth = 150;
   Console.WindowHeight = 61;

在我的电脑上几乎按照我想要的方式工作,但在其他一些电脑上会出现错误。 我该怎么做才能最大化控制台?


你遇到了什么错误?你读过它了吗? - SLaks
1
http://msdn.microsoft.com/en-us/library/windows/desktop/ms683193(v=vs.85).aspx - SLaks
阅读此内容并查看SLaks的评论:https://dev59.com/Imsz5IYBdhLWcg3wxq0V - Bassam Alugili
1
@SLaks 我这里没有具体的错误信息,但大概是关于屏幕尺寸比当前格式要小或者大之类的问题。 - user26830
@BassamAlugili 感谢您提供的链接,但这只是针对尺寸而不是最大化它(就像点击右上角的最大化按钮)。 - user26830
4个回答

37

无法使用CLR。需要导入Win32 API调用并操纵你的容器窗口。以下内容可能有所帮助。

using System.Diagnostics;
using System.Runtime.InteropServices;

[DllImport("user32.dll")]
public static extern bool ShowWindow(System.IntPtr hWnd, int cmdShow);

private static void Maximize()
{
    Process p = Process.GetCurrentProcess();
    ShowWindow(p.MainWindowHandle, 3); //SW_MAXIMIZE = 3
}

1
哇,我正在回忆起丹·阿普尔曼(Dan Appleman)的经历。干得好,谢谢。 - ruffin
我不得不重新启用VB.NET的美观性,但最终我让它工作了,所以谢谢! :) - mbm29414

19
    [DllImport("kernel32.dll", ExactSpelling = true)]

    private static extern IntPtr GetConsoleWindow();
    private static IntPtr ThisConsole = GetConsoleWindow();

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]

    private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    private const int HIDE = 0;
    private const int MAXIMIZE = 3;
    private const int MINIMIZE = 6;
    private const int RESTORE = 9;


    static void Main(string[] args)
    {
       ShowWindow(ThisConsole, MINIMIZE);
    }

3
请解释代码如何解决问题。不建议只提供代码答案。 - zero323
1
这个答案即使在没有调试器的情况下启动控制台应用程序也可以工作,而被接受的答案则不行。另一个选项是使用user32.dll中的FindWindowByCaption函数。 - nawfal
3
我认为应该是ShowWindow(ThisConsole, MAXIMIZE); - Mojtaba

1
Console.SetWindowSize(Console.LargestWindowWidth, Console.LargestWindowHeight)

1
这适用于.NET 6控制台应用程序:
using System.Runtime.InteropServices;

[DllImport("kernel32.dll", ExactSpelling = true)]

static extern IntPtr GetConsoleWindow();
IntPtr ThisConsole = GetConsoleWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]

static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
const int HIDE = 0;
const int MAXIMIZE = 3;
const int MINIMIZE = 6;
const int RESTORE = 9;

ShowWindow(ThisConsole, MAXIMIZE);

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