我尝试使用 C# 命令最大化控制台 .NET 应用程序,但它不起作用。
这是我尝试过的: 示例1:
using System;
using System.Runtime.InteropServices;
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int MAXIMIZE = 3;
private const int MINIMIZE = 6;
static void Main(string[] args)
{
ShowWindow(GetConsoleWindow(), MAXIMIZE);
Console.ReadKey();
}
在第一个示例中,如果您输入“MINIMIZE”而不是“MAXIMIZE”,它会最小化,但不会最大化...
示例2:
[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
}
static void Main(string[] args)
{
Maximize();
Console.ReadKey();
}
您的代码在 Windows 10 中运行良好,但如果您在 Win11 中选择 Windows Terminal,您的代码将无法运行。
如果您使用的是Win11:
请打开设置=>隐私和安全=>开发人员=>终端=>更改为Windows控制台主机
此时,您可以再次使用您提供的代码来最大化控制台程序。
using System;
using System.Runtime.InteropServices;
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int MAXIMIZE = 3;
private const int MINIMIZE = 6;
static void Main(string[] args)
{
ShowWindow(GetConsoleWindow(), MAXIMIZE);
Console.ReadKey();
}